
local template = require('pl.template')
local file = require('pl.file')
local path = require('pl.path')
local class = require('pl.class')

local serials = require('luamods.modbus_scan.serials')

local DeviceCreator = class()

function DeviceCreator:_init(device_template_path, device_dir)
    self.device_template_path = device_template_path
    self.device_dir = device_dir
end

function DeviceCreator:prepare()
    local dev_template_content, err = file.read(self.device_template_path)
    if err then
        return err
    end

    self.dev_template_content = dev_template_content
end

function DeviceCreator:create_slave_devices(slaves, host, service)
    local errors = {}

    for _, slave in ipairs(slaves) do
        for i, t in ipairs(slave.templates) do
            local new_serial = serials.generate_new_serial()

            local dev_content = template.substitute(self.dev_template_content, {
                serial = new_serial,
                label = t.type,
                template = t.template_file,
                host = host,
                service = service,
                slave = slave.number
            })

            local _, err = file.write(path.join(self.device_dir, new_serial .. '.xml'), dev_content)
            if err then
                table.insert(errors, err)
            end
        end
    end

    if #errors > 0 then
        local err = ''
        for _, e in ipairs(errors) do
            err = err .. '\n'
        end
    else
        return nil
    end
end

return DeviceCreator
