-- vi: ft=lua

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)

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 split(s)
    chunks = {}

    for substring in s:gmatch("%S+") do
       table.insert(chunks, substring)
    end
    return chunks
end

function recv()
    while true do
        local id, data = rednet.receive()
        print("Message from " .. id .. ": " .. dump(data))
        write("> ")
    end
end

function move_control(turtle_id)
    while true do
        local event, param = os.pullEvent("key")
        if event == "key" then
            -- print("Got key: " .. param)
            if param == 14 then
                break
            elseif param == 17 then
                rednet.send(turtle_id, {"eval", "turtle.forward()"})
            elseif param == 30 then
                rednet.send(turtle_id, {"eval", "turtle.turnLeft()"})
            elseif param == 31 then
                rednet.send(turtle_id, {"eval", "turtle.back()"})
            elseif param == 32 then
                rednet.send(turtle_id, {"eval", "turtle.turnRight()"})
            elseif param == 57 then
                rednet.send(turtle_id, {"eval", "turtle.up()"})
            elseif param == 29 then
                rednet.send(turtle_id, {"eval", "turtle.down()"})
            end
        end
    end
end

function control()
    while true do
        write("> ")
        local input = split(read())
        -- print(dump(input))
        if input[1] == 'lookup' then
            print(rednet.lookup("rmm", input[2]))
        elseif input[1] == 'ping' then
            rednet.send(tonumber(input[2]), 'ping')
        elseif input[1] == 'eval' then
            rednet.send(tonumber(input[2]), {"eval", input[3]})
        elseif input[1] == 'send' then
            rednet.send(tonumber(input[2]), input[3])
        elseif input[1] == 'move' then
            move_control(tonumber(input[2]))
        else
            print("Unknown command")
        end
    end
end

rednet.host("rmm", "master")

while true do
    parallel.waitForAny(recv, control)
end

rednet.close(modemSide)