-- controller.lua
-- PC controller for lane quarry

local PROTOCOL = "lane_quarry"
local turtles = {}

local function openModem()
    for _, side in ipairs(peripheral.getNames()) do
        if peripheral.getType(side) == "modem" then
            rednet.open(side)
            return
        end
    end
    error("No modem found")
end

local monitor = peripheral.find("monitor")
if monitor then monitor.setTextScale(0.5) end

local function getScreen()
    return monitor or term
end

local function draw()
    local s = getScreen()
    s.clear()
    s.setCursorPos(1, 1)

    local total = 0

    s.write("LANE QUARRY CONTROL")
    s.setCursorPos(1, 2)
    s.write("===================")

    for i = 1, 6 do
        local t = turtles[tostring(i)]
        s.setCursorPos(1, i + 3)

        if t then
            total = total + (t.blocks or 0)
            s.write(
                "T" .. i ..
                " | " .. tostring(t.status) ..
                " | Blocks: " .. tostring(t.blocks) ..
                " | Fuel: " .. tostring(t.fuel) ..
                " | South: " .. tostring(t.z) ..
                " | Y: " .. tostring(t.y)
            )
        else
            s.write("T" .. i .. " | offline")
        end
    end

    s.setCursorPos(1, 11)
    s.write("TOTAL BLOCKS MINED: " .. total)

    if not monitor then
        s.setCursorPos(1, 13)
        s.write("Command > ")
    end
end

local function sendCommand(tbl)
    rednet.broadcast(tbl, PROTOCOL)
end

local function listener()
    while true do
        local sender, msg = rednet.receive(PROTOCOL)

        if type(msg) == "table" and msg.id then
            turtles[tostring(msg.id)] = msg
            draw()
        end
    end
end

local function inputLoop()
    while true do
        draw()

        local input = read()
        local parts = {}

        for word in string.gmatch(input, "%S+") do
            table.insert(parts, word)
        end

        local cmd = parts[1]

        if cmd == "start" then
            sendCommand({
                cmd = "start",
                length = tonumber(parts[2]) or 500,
                depth = tonumber(parts[3]) or 314
            })

        elseif cmd == "pause" then
            sendCommand({cmd = "pause"})

        elseif cmd == "resume" then
            sendCommand({cmd = "resume"})

        elseif cmd == "stop" then
            sendCommand({cmd = "stop"})

        elseif cmd == "status" then
            sendCommand({cmd = "status"})

        elseif cmd == "empty" then
            sendCommand({cmd = "empty"})

        elseif cmd == "reset" then
            sendCommand({cmd = "reset"})

        elseif cmd == "help" then
            print("Commands:")
            print("start 500 314")
            print("pause")
            print("resume")
            print("stop")
            print("status")
            print("empty")
            print("reset")
            sleep(4)
        end
    end
end

openModem()
draw()
parallel.waitForAny(listener, inputLoop)