-- vi: ft=lua

local hostname = "de_store" .. os.getComputerID()

function dump(o)
    if o == nil then
        return ""
    end

    if type(o) == 'table' then
        local s = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then k = '"'..k..'"' end
            s = s .. '['..k..'] = ' .. dump(v) .. ','
        end
        return s .. '} '
    end

    return tostring(o)
end

function recv()
    while true do
        local event, id, data = os.pullEvent()
        if event == "rednet_message" then
            print(id .. " (" .. event .. ")> " .. dump(data))
            if type(data) == 'table' then
                if data[1] == 'eval' then
                    local cmd_fn, err = loadstring(data[2])
                    if not cmd_fn then
                        print("Failed to compile '" .. data[2] .. "': " .. err)
                        rednet.send(id, "Failed to compile '" .. data[2] .. "': " .. err)
                    else
                        local success, output = pcall(cmd_fn)
                        if success then
                            if output then
                                print("Command output from '" .. data[2] .. "': " .. dump(output))
                                rednet.send(id, "Command output from '" .. data[2] .. "': " .. dump(output))
                            else
                                print("There is no command output from '" .. data[2] .. "'")
                                rednet.send(id, "There is no command output from '" .. data[2] .. "'")
                            end
                        else
                            print("Runtime error: " .. output)
                            rednet.send(id, "Runtime error: " .. output)
                        end
                    end
                end
            elseif type(data) == 'string' then
                if data == 'ping' then
                    print("Pong!")
                    rednet.send(id, "Pong!")
                elseif data == 'get_stats' then
                    local stats = {
                        'energyStored', de_store_peri.getEnergyStored(),
                        'maxEnergyStored', de_store_peri.getMaxEnergyStored(),
                        'transferPerTick', de_store_peri.getTransferPerTick(),
                    } 
                    print("Stats: " .. dump(stats))
                    rednet.send(id, stats)
                end
            end
        end
    end
end

local sides = peripheral.getNames()
for i = 1, #sides do
    if peripheral.getType(sides[i]) == "modem" then
        modemSide = sides[i]
        break
    end
end

rednet.open(modemSide)
rednet.host("rmm", hostname)

de_store_peri = peripheral.wrap("back")

parallel.waitForAny(recv)

rednet.close(modemSide)