-- Thorium Reactors dashboard for CC: Tweaked
--
-- Shows and controls the reactor, all turbines (up to 16) and all heat exchangers on advanced monitors.
-- Needs: one advanced computer, a wired modem network (or direct contact) with
--   * a block of the reactor (thorium_reactor), the turbines are controlled through the reactor
--   * a block of every heat exchanger (thorium_thermal)
--   * 1 to 5 advanced monitors (3x3 or bigger, touch them to use the buttons)
--
-- Automatic: monitor 1 = reactor, the last monitor = heat exchangers, all monitors in between = turbines.
-- The turbines are spread over all turbine monitors (a turbine card is 14 characters wide, up to 10 per row).
-- With less than 3 monitors the views switch automatically every few seconds.
-- To choose what every monitor shows use CONFIG.monitors below.
-- Start the reactor with START, then press RUN as soon as the start up is finished (RUN is ignored before that).
-- Save it as "startup.lua" or run it with "thorium_dashboard".

local CONFIG = {
    -- Which monitor shows what. nil = automatic. Use the names of the monitors ("monitor_4", see
    -- peripheral.getNames()), several monitors for the turbines are given as a list:
    --   monitors = { reactor = "monitor_0", turbines = { "monitor_1", "monitor_2", "monitor_3" }, thermal = "monitor_4" }
    monitors = {
        reactor = nil,
        turbines = nil,
        thermal = nil,
    },
    maxMonitors = 5,        -- how many monitors are used automatically
    maxTurbinesPerRow = 10, -- turbine cards next to each other on one monitor
    textScale = 0.5,   -- 0.5 = a lot of space, 1 = bigger text
    refresh = 1,       -- seconds between two updates (the screen only redraws what changed)
    rotate = 8,        -- seconds per view if there are less than 3 monitors
    flowStep = 50,     -- mB/t per click of the flow buttons of the turbines
    loadStep = 5,      -- % per click of the fuel load buttons
    rodStep = 10,      -- % per click of the control rod buttons
}

-- ---------------------------------------------------------------- helpers

local function fmt(n)
    n = tonumber(n) or 0
    local a = math.abs(n)
    if a >= 1e9 then return string.format("%.2fG", n / 1e9) end
    if a >= 1e6 then return string.format("%.2fM", n / 1e6) end
    if a >= 1e4 then return string.format("%.1fk", n / 1e3) end
    if a == math.floor(a) then return string.format("%d", n) end
    return string.format("%.1f", n)
end

local function frac(value, max)
    value, max = tonumber(value) or 0, tonumber(max) or 0
    if max <= 0 then return 0 end
    return math.max(0, math.min(1, value / max))
end

-- green when f is high ("good"), red when it is low. invert = true: red when high
local function traffic(f, invert)
    if invert then f = 1 - f end
    if f > 0.6 then return colors.green end
    if f > 0.3 then return colors.yellow end
    return colors.red
end

local function duration(ticks)
    ticks = tonumber(ticks) or -1
    if ticks < 0 then return "-" end
    local s = math.floor(ticks / 20)
    return string.format("%dh %02dm %02ds", math.floor(s / 3600), math.floor(s / 60) % 60, s % 60)
end

local function call(fn, ...)
    local ok, a = pcall(fn, ...)
    if ok then return a end
    return nil
end

local function clamp(v, lo, hi) return math.max(lo, math.min(hi, v)) end

-- ---------------------------------------------------------------- canvas
-- Everything is drawn into a buffer first. Only the rows that really changed are sent to
-- the monitor, so nothing flickers.

local function newCanvas(mon, name)
    local c = { mon = mon, name = name, buttons = {}, frame = 0 }
    local ch, fg, bg, prev = {}, {}, {}, {}

    local function reset()
        c.w, c.h = mon.getSize()
        ch, fg, bg, prev = {}, {}, {}, {}
        for y = 1, c.h do ch[y], fg[y], bg[y] = {}, {}, {} end
    end
    reset()

    -- call before drawing a new frame
    function c.begin()
        local w, h = mon.getSize()
        if w ~= c.w or h ~= c.h then reset() end
        for y = 1, c.h do
            local a, b, d = ch[y], fg[y], bg[y]
            for x = 1, c.w do a[x], b[x], d[x] = " ", colors.white, colors.black end
        end
        c.buttons = {}
        c.frame = c.frame + 1
    end

    function c.text(x, y, str, fgc, bgc)
        if y < 1 or y > c.h then return end
        str = tostring(str)
        for i = 1, #str do
            local px = x + i - 1
            if px >= 1 and px <= c.w then
                ch[y][px] = str:sub(i, i)
                fg[y][px] = fgc or colors.white
                if bgc then bg[y][px] = bgc end
            end
        end
    end

    function c.fill(x, y, w, bgc, h)
        for yy = y, y + (h or 1) - 1 do
            if yy >= 1 and yy <= c.h then
                for px = math.max(1, x), math.min(c.w, x + w - 1) do
                    ch[yy][px], bg[yy][px] = " ", bgc
                end
            end
        end
    end

    -- a bar with a text in the middle
    function c.bar(x, y, w, f, color, label)
        if w < 1 then return end
        label = tostring(label or "")
        if #label > w then label = label:sub(1, w) end
        local pad = math.floor((w - #label) / 2)
        label = string.rep(" ", pad) .. label .. string.rep(" ", w - #label - pad)
        local n = math.floor(w * f + 0.5)
        for i = 1, w do
            c.text(x + i - 1, y, label:sub(i, i), colors.white, i <= n and color or colors.gray)
        end
    end

    -- a touch button, h rows high, the action is called when it is touched
    function c.button(x, y, w, h, label, color, action)
        c.fill(x, y, w, color, h)
        label = tostring(label):sub(1, w)
        local lx = x + math.floor((w - #label) / 2)
        c.text(lx, y + math.floor((h - 1) / 2), label, colors.white, color)
        c.buttons[#c.buttons + 1] = { x = x, y = y, w = w, h = h, action = action }
    end

    -- an invisible touch area
    function c.area(x, y, w, h, action)
        c.buttons[#c.buttons + 1] = { x = x, y = y, w = w, h = h, action = action }
    end

    function c.header(title, right, color)
        color = color or colors.green
        c.fill(1, 1, c.w, color)
        c.text(2, 1, title, colors.white, color)
        if right then c.text(c.w - #right, 1, right, colors.white, color) end
    end

    function c.hit(x, y)
        for i = #c.buttons, 1, -1 do
            local b = c.buttons[i]
            if x >= b.x and x < b.x + b.w and y >= b.y and y < b.y + b.h then return b end
        end
    end

    -- sends the changed rows to the monitor
    function c.flush()
        for y = 1, c.h do
            local t, f, b = {}, {}, {}
            for x = 1, c.w do
                t[x] = ch[y][x]
                f[x] = colors.toBlit(fg[y][x])
                b[x] = colors.toBlit(bg[y][x])
            end
            local row = table.concat(t) .. "|" .. table.concat(f) .. "|" .. table.concat(b)
            if prev[y] ~= row then
                prev[y] = row
                mon.setCursorPos(1, y)
                mon.blit(table.concat(t), table.concat(f), table.concat(b))
            end
        end
    end

    return c
end

-- ---------------------------------------------------------------- view: reactor

-- a rod is drawn with two block characters that leave a small gap at the bottom of the row
local ROD = "\143\143"
local selectedRod = nil   -- 0 based index of the selected control rod, nil = all rods

local function drawCore(c, x, y, rods, spacing)
    -- The core as in the game: 9x9 fuel rods and 8x8 control rods between them, turned by 45 degrees.
    -- A fuel rod (row r, column c) sits at x = spacing * (c - r), y = r + c,
    -- the control rod at the corner between four fuel rods one row lower.
    local mid = spacing * 8
    for r = 0, 8 do
        for col = 0, 8 do
            local v = rods.fuel[r * 9 + col + 1] or 0
            local color = colors.gray
            if v > 0 then color = v >= 60 and colors.lime or (v >= 30 and colors.yellow or colors.orange) end
            c.text(x + mid + spacing * (col - r), y + r + col, ROD, color, colors.black)
        end
    end
    for r = 0, 7 do
        for col = 0, 7 do
            local index = r * 8 + col
            local v = rods.control[index + 1] or 0
            local color = v >= 50 and colors.blue or (v > 0 and colors.cyan or colors.lightBlue)
            local px, py = x + mid + spacing * (col - r), y + r + col + 1
            c.text(px, py, ROD, selectedRod == index and colors.white or color, colors.black)
            c.area(px, py, 2, 1, function() selectedRod = (selectedRod ~= index) and index or nil end)
        end
    end
end

local function viewReactor(c, reactor)
    local info = reactor and call(reactor.getReactorInfo) or nil
    if not info then
        c.header("Reactor", "no connection", colors.red)
        c.text(2, 3, "No thorium_reactor found.", colors.red)
        return
    end
    if not info.assembled then
        c.header("Reactor", "NOT ASSEMBLED", colors.red)
        c.text(2, 3, "The reactor is not assembled.", colors.red)
        return
    end

    local stateColor = ({ running = colors.green, starting = colors.yellow, stop = colors.red })[info.state] or colors.gray
    c.header("Thorium Reactor", string.upper(info.state) .. (info.scrammed and "  SCRAM" or ""), info.scrammed and colors.red or stateColor)

    local spacing = (c.w >= 100) and 3 or 2
    local mapW = spacing * 16 + 2
    local sideMap = c.w >= mapW + 24
    local bw = sideMap and (c.w - mapW - 4) or (c.w - 3)
    bw = clamp(bw, 20, 44)

    local y = 3
    if info.notification and info.notification ~= "" then
        c.text(2, y, info.notification, colors.orange)
    else
        c.text(2, y, "Running for " .. duration(info.runningSince), colors.lightGray)
    end
    y = y + 2

    local function row(label, f, color, text)
        c.bar(2, y, bw, f, color, label .. "  " .. text)
        y = y + 1
    end
    row("Temp", frac(info.temperature - 22, 949), traffic(frac(info.temperature - 22, 949), true), string.format("%.0f/%.0f C", info.temperature, info.targetTemperature))
    row("Load", info.load / 100, colors.orange, string.format("%.0f %%", info.load))
    row("Fuel", info.fuel / 100, colors.lime, string.format("%.1f %%", info.fuel))
    row("Control", info.controlRods / 100, colors.blue, string.format("%.1f %%", info.controlRods))
    row("Integrity", info.status / 100, traffic(info.status / 100, false), string.format("%.1f %%", info.status))
    row("Salt", frac(info.fluidIn.amount, info.fluidIn.capacity), colors.cyan, fmt(info.fluidIn.amount) .. "/" .. fmt(info.fluidIn.capacity))
    row("Hot salt", frac(info.fluidOut.amount, info.fluidOut.capacity), colors.red, fmt(info.fluidOut.amount) .. "/" .. fmt(info.fluidOut.capacity))
    y = y + 1
    c.text(2, y, "Contamination " .. fmt(info.contamination) .. " uSv/h", info.contamination > 0 and colors.red or colors.green)
    c.text(2, y + 1, "Turbines " .. info.turbineCount, colors.lightGray)
    y = y + 3

    -- controls
    local function buttonRow(labels, h)
        local n = #labels
        local gap = 1
        local w = math.floor((bw - gap * (n - 1)) / n)
        for i, b in ipairs(labels) do
            c.button(2 + (i - 1) * (w + gap), y, w, h, b[1], b[2], b[3])
        end
        y = y + h + 1
    end

    buttonRow({
        { "START", colors.yellow, function() reactor.setReactorState("starting") end },
        { "RUN", colors.green, function() reactor.setReactorState("running") end },
        { "STOP", colors.orange, function() reactor.setReactorState("stop") end },
    }, 3)
    buttonRow({
        { info.scrammed and "RESET SCRAM" or "SCRAM", colors.red, function() reactor.setReactorScrammed(not info.scrammed) end },
    }, 3)

    c.text(2, y, "Fuel load: " .. info.targetLoad .. " %", colors.lightGray); y = y + 1
    buttonRow({
        { "-" .. CONFIG.loadStep, colors.gray, function() reactor.setReactorTargetLoadSet(clamp(info.targetLoad - CONFIG.loadStep, 0, 100)) end },
        { "+" .. CONFIG.loadStep, colors.gray, function() reactor.setReactorTargetLoadSet(clamp(info.targetLoad + CONFIG.loadStep, 0, 100)) end },
    }, 3)

    local rods = call(reactor.getRods)
    local label = "Control rods: all"
    local current = nil
    if selectedRod and rods then
        current = rods.targetControl[selectedRod + 1] or 0
        label = "Control rod #" .. (selectedRod + 1) .. ": " .. current .. " %"
    end
    c.text(2, y, label, selectedRod and colors.cyan or colors.lightGray); y = y + 1
    local function setRods(value)
        value = clamp(value, 0, 100)
        if selectedRod then reactor.setTargetControlRodStatus(selectedRod, value)
        else reactor.setAllTargetControlRodStatus(value) end
    end
    local base = current or info.controlRods
    buttonRow({
        { "-" .. CONFIG.rodStep, colors.blue, function() setRods(math.floor(base) - CONFIG.rodStep) end },
        { "+" .. CONFIG.rodStep, colors.blue, function() setRods(math.floor(base) + CONFIG.rodStep) end },
        { "0", colors.gray, function() setRods(0) end },
        { "100", colors.gray, function() setRods(100) end },
    }, 3)

    -- the core map
    if rods then
        if sideMap then
            local x = bw + 4
            c.text(x, 3, "Core (touch a blue rod to select it)", colors.lightGray)
            drawCore(c, x, 5, rods, spacing)
            c.text(x, 23, "Fuel", colors.lime)
            c.text(x + 6, 23, "Control", colors.blue)
        elseif c.h >= y + 18 then
            drawCore(c, 2, y + 1, rods, spacing)
        end
    end
end

-- ---------------------------------------------------------------- view: turbines (portrait cards)

local CARD_W, BODY = 14, 8

local function drawTurbine(c, x, y, t, reactor, flowStep)
    local color, state = colors.gray, "NOT BUILT"
    if t.assembled then
        if t.warning and t.warning ~= "" then color, state = colors.red, "WARNING"
        elseif t.active and t.coilsEngaged then color, state = colors.green, "RUNNING"
        elseif t.active then color, state = colors.yellow, "NO COILS"
        else color, state = colors.orange, "STOPPED" end
    end
    c.fill(x, y, CARD_W, color)
    c.text(x + 1, y, "#" .. t.turbineId .. " " .. state, colors.white, color)
    if not t.assembled then return end

    -- the turbine from the side: casing, rotor and blades (the blades move when it turns)
    local spinning = (t.speed or 0) > 1
    local phase = spinning and (c.frame % 2) or 0
    local blade = frac(t.speed, 2000)
    local bladeColor = blade > 0.66 and colors.cyan or (blade > 0.2 and colors.lightBlue or colors.blue)
    for r = 1, BODY do
        local by = y + r
        c.fill(x, by, 1, colors.gray)
        c.fill(x + CARD_W - 1, by, 1, colors.gray)
        c.fill(x + 1, by, CARD_W - 2, colors.black)
        c.fill(x + 6, by, 2, colors.lightGray)          -- rotor
        if r > 1 and r < BODY and r % 2 == 0 then          -- blades
            local pattern = ((r / 2 + phase) % 2 == 0) and "/\\/\\/" or "\\/\\/\\"
            c.text(x + 1, by, pattern, bladeColor, colors.black)
            c.text(x + 8, by, pattern, bladeColor, colors.black)
        end
    end
    c.fill(x, y + BODY + 1, CARD_W, colors.gray)

    local ry = y + BODY + 2
    c.bar(x, ry, CARD_W, frac(t.speed, 2000), colors.blue, string.format("%.0f rpm", t.speed))
    c.bar(x, ry + 1, CARD_W, frac(t.currentFlow, t.maxFlow), colors.cyan, string.format("%.0f/%.0f", t.currentFlow, t.targetFlow))
    c.text(x, ry + 2, fmt(t.generation) .. " FE/t", colors.yellow)
    c.text(x + 9, ry + 2, "h" .. (t.height or 0), colors.gray)
    if t.warning and t.warning ~= "" then
        c.text(x, ry + 3, t.warning, colors.red)
    else
        c.text(x, ry + 3, string.format("max %d mB/t", t.maxFlow or 0), colors.gray)
    end

    local id = t.turbineId
    c.button(x, ry + 4, 6, 2, t.active and "OFF" or "ON", t.active and colors.orange or colors.green, function() reactor.setTurbineActive(id, not t.active) end)
    c.button(x + 7, ry + 4, 7, 2, t.coilsEngaged and "COIL ON" or "COIL OFF", t.coilsEngaged and colors.green or colors.gray, function() reactor.setTurbineCoilsEngaged(id, not t.coilsEngaged) end)
    c.button(x, ry + 6, 6, 2, "-" .. flowStep, colors.blue, function() reactor.setTurbineTargetFlow(id, clamp(t.targetFlow - flowStep, 0, t.maxFlow)) end)
    c.button(x + 7, ry + 6, 7, 2, "+" .. flowStep, colors.blue, function() reactor.setTurbineTargetFlow(id, clamp(t.targetFlow + flowStep, 0, t.maxFlow)) end)
end

local CARD_H = BODY + 10

-- how many turbine cards fit on a canvas
local function turbineLayout(c)
    local perRow = clamp(math.floor((c.w - 1) / (CARD_W + 2)), 1, CONFIG.maxTurbinesPerRow)
    local rows = c.h >= 6 + CARD_H and math.floor((c.h - 6 - CARD_H) / (CARD_H + 1)) + 1 or 0
    return perRow, math.max(0, rows)
end

local function turbineCapacity(c)
    local perRow, rows = turbineLayout(c)
    return perRow * rows
end

local function viewTurbines(c, reactor, ctx)
    local list = reactor and call(reactor.getTurbines) or nil
    if not list then
        c.header("Turbines", "no connection", colors.red)
        c.text(2, 3, "No thorium_reactor found.", colors.red)
        return
    end
    local skip = ctx and ctx.skip or 0
    local perRow, rows = turbineLayout(c)
    local cap = perRow * rows
    local first, last = skip + 1, math.min(#list, skip + cap)

    local total, active = 0, 0
    for _, t in ipairs(list) do
        if t.assembled and t.coilsEngaged then total = total + (t.generation or 0) end
        if t.assembled and t.active then active = active + 1 end
    end
    local range = (#list > cap or skip > 0) and (" #" .. (first - 1) .. "-" .. (last - 1)) or ""
    c.header("Turbines " .. active .. "/" .. #list .. " active" .. range, fmt(total) .. " FE/t")

    -- buttons for all turbines
    local bw = math.floor((c.w - 2 - 3) / 4)
    c.button(2, 3, bw, 3, "ALL ON", colors.green, function() reactor.setAllTurbinesActive(true) end)
    c.button(2 + (bw + 1), 3, bw, 3, "ALL OFF", colors.orange, function() reactor.setAllTurbinesActive(false) end)
    local step = CONFIG.flowStep
    c.button(2 + 2 * (bw + 1), 3, bw, 3, "ALL -" .. step, colors.blue, function()
        for _, t in ipairs(list) do if t.assembled then reactor.setTurbineTargetFlow(t.turbineId, clamp(t.targetFlow - step, 0, t.maxFlow)) end end
    end)
    c.button(2 + 3 * (bw + 1), 3, bw, 3, "ALL +" .. step, colors.blue, function()
        for _, t in ipairs(list) do if t.assembled then reactor.setTurbineTargetFlow(t.turbineId, clamp(t.targetFlow + step, 0, t.maxFlow)) end end
    end)

    if #list == 0 then c.text(2, 7, "The reactor has no turbines.", colors.orange) return end
    if cap == 0 then c.text(2, 7, "The monitor is too small for a turbine.", colors.orange) return end
    if first > #list then c.text(2, 7, "No more turbines for this monitor.", colors.gray) return end
    if ctx and ctx.lastMonitor and #list > skip + cap then
        c.text(2, 6, (#list - skip - cap) .. " more turbines do not fit, add a monitor.", colors.orange)
    end

    local x0 = 2 + math.floor((c.w - 1 - perRow * (CARD_W + 2) + 2) / 2)
    for i = first, last do
        local n = i - skip - 1
        local col, rowN = n % perRow, math.floor(n / perRow)
        drawTurbine(c, x0 + col * (CARD_W + 2), 7 + rowN * (CARD_H + 1), list[i], reactor, step)
    end
end

-- ---------------------------------------------------------------- view: heat exchangers

local function findThermals()
    local found, seen = {}, {}
    for _, name in ipairs(peripheral.getNames()) do
        if peripheral.hasType(name, "thorium_thermal") then
            local p = peripheral.wrap(name)
            local info = p and call(p.getInfo)
            if info and info.assembled then
                local key = info.position.x .. "," .. info.position.y .. "," .. info.position.z
                if not seen[key] then seen[key] = true; found[#found + 1] = info end
            end
        end
    end
    table.sort(found, function(a, b) return a.position.x .. a.position.y .. a.position.z < b.position.x .. b.position.y .. b.position.z end)
    return found
end

local THERMAL_W, GAUGE_H = 20, 10

-- a vertical gauge that fills from the bottom
local function gauge(c, x, y, f, color, label, value)
    local filled = math.floor(GAUGE_H * f + 0.5)
    for r = 1, GAUGE_H do
        c.fill(x + 1, y + r - 1, 3, (GAUGE_H - r) < filled and color or colors.gray)
    end
    c.text(x + math.floor((5 - #label) / 2), y + GAUGE_H, label, colors.lightGray)
    value = tostring(value)
    c.text(x + math.floor((5 - #value) / 2), y + GAUGE_H + 1, value, colors.white)
end

local function drawThermal(c, x, y, i, n)
    local color = i.working and colors.green or colors.orange
    c.fill(x, y, THERMAL_W, color)
    c.text(x + 1, y, string.format("#%d %s %s", n, string.upper(i.size), i.working and "WORKING" or "IDLE"), colors.white, color)
    local gy = y + 1
    local tf = frac(i.temperature, i.heatCapacity)
    gauge(c, x, gy, tf, traffic(tf, true), "TEMP", i.temperature .. "C")
    gauge(c, x + 5, gy, frac(i.salt.amount, i.salt.capacity), colors.red, "SALT", fmt(i.salt.amount))
    gauge(c, x + 10, gy, frac(i.water.amount, i.water.capacity), colors.blue, "WATER", fmt(i.water.amount))
    gauge(c, x + 15, gy, frac(i.steam.amount, i.steam.capacity), colors.lightGray, "STEAM", fmt(i.steam.amount))
    local iy = gy + GAUGE_H + 2
    c.text(x, iy, fmt(i.produced) .. " mB/t steam", colors.yellow)
    c.text(x, iy + 1, "salt " .. fmt(i.saltRate) .. "  water " .. fmt(i.waterRate), colors.lightGray)
    c.text(x, iy + 2, string.format("%d, %d, %d", i.position.x, i.position.y, i.position.z), colors.gray)
    -- flames under the exchanger while it works
    if i.working then
        for k = 0, THERMAL_W - 1 do
            local on = (k + c.frame) % 3 ~= 0
            c.text(x + k, iy + 3, on and "^" or " ", (k + c.frame) % 2 == 0 and colors.orange or colors.red)
        end
    end
end

local function viewThermals(c)
    local list = findThermals()
    local produced = 0
    for _, i in ipairs(list) do produced = produced + (i.produced or 0) end
    c.header("Heat exchangers (" .. #list .. ")", fmt(produced) .. " mB/t steam")
    if #list == 0 then
        c.text(2, 3, "No assembled thorium_thermal found.", colors.red)
        return
    end

    local perRow = math.max(1, math.floor((c.w - 1) / (THERMAL_W + 2)))
    local x0 = 2 + math.floor((c.w - 1 - perRow * (THERMAL_W + 2) + 2) / 2)
    for n, i in ipairs(list) do
        local col, rowN = (n - 1) % perRow, math.floor((n - 1) / perRow)
        local y = 3 + rowN * (GAUGE_H + 8)
        if y + GAUGE_H + 7 <= c.h + 1 then drawThermal(c, x0 + col * (THERMAL_W + 2), y, i, n) end
    end
end

-- ---------------------------------------------------------------- main

local views = {
    { name = "reactor", draw = viewReactor },
    { name = "turbines", draw = viewTurbines },
    { name = "thermal", draw = viewThermals },
}

local function toList(v)
    if v == nil then return {} end
    if type(v) == "string" then return { v } end
    return v
end

local function setupMonitors()
    local names = {}
    for _, name in ipairs(peripheral.getNames()) do
        if peripheral.hasType(name, "monitor") then names[#names + 1] = name end
    end
    table.sort(names)
    local list = {}
    for _, name in ipairs(names) do
        local m = peripheral.wrap(name)
        m.setTextScale(CONFIG.textScale)
        m.setBackgroundColor(colors.black)
        m.clear()
        list[#list + 1] = { name = name, canvas = newCanvas(m, name) }
    end
    return list
end

local monitors = setupMonitors()
if #monitors == 0 then error("No monitor found. Place an advanced monitor next to the computer or the wired modem.", 0) end
local reactor = peripheral.find("thorium_reactor")
local startTime = os.clock()
local shown = {}   -- monitor name -> view that is shown at the moment

local function findMonitor(name)
    for _, m in ipairs(monitors) do if m.name == name then return m end end
end

-- returns a list of { m = monitor, v = view }
local function assign()
    local page = math.floor((os.clock() - startTime) / CONFIG.rotate)
    local used, assignment, open = {}, {}, {}
    for _, v in ipairs(views) do
        local any = false
        for _, name in ipairs(toList(CONFIG.monitors[v.name])) do
            local m = findMonitor(name)
            if m and not used[name] then used[name] = true; any = true; assignment[#assignment + 1] = { m = m, v = v } end
        end
        if not any then open[#open + 1] = v end
    end
    local free = {}
    for _, m in ipairs(monitors) do
        if not used[m.name] and #free < CONFIG.maxMonitors then free[#free + 1] = m end
    end
    if #free >= #open then
        -- reactor first, heat exchangers last, everything in between shows turbines
        local ordered = {}
        for _, v in ipairs(open) do ordered[#ordered + 1] = v end
        local extra = #free - #open
        local k = 1
        for _, v in ipairs(ordered) do
            assignment[#assignment + 1] = { m = free[k], v = v }
            k = k + 1
            if v.name == "turbines" then
                for _ = 1, extra do assignment[#assignment + 1] = { m = free[k], v = v }; k = k + 1 end
                extra = 0
            end
        end
    elseif #open > 0 then
        -- not enough monitors: the views rotate
        for i, m in ipairs(free) do assignment[#assignment + 1] = { m = m, v = open[((i - 1) + page) % #open + 1] } end
    end
    return assignment
end

local function redraw()
    if not reactor then reactor = peripheral.find("thorium_reactor") end
    local list = assign()
    -- the turbine monitors share the turbines: every monitor shows the next ones
    local skip, turbineMonitors = 0, {}
    for _, a in ipairs(list) do if a.v.name == "turbines" then turbineMonitors[#turbineMonitors + 1] = a end end
    for i, a in ipairs(turbineMonitors) do
        a.ctx = { skip = skip, lastMonitor = (i == #turbineMonitors) }
        skip = skip + turbineCapacity(a.m.canvas)
    end
    for _, a in ipairs(list) do
        local c = a.m.canvas
        c.begin()
        local ok, err = pcall(a.v.draw, c, reactor, a.ctx)
        if not ok then c.text(1, 1, "Error: " .. tostring(err), colors.red) end
        c.flush()
        shown[a.m.name] = c
    end
end

local function touch(name, x, y)
    local c = shown[name]
    local b = c and c.hit(x, y)
    if b then pcall(b.action) end
end

-- a failing redraw (monitor or peripheral gone, chunk unloaded...) must never stop the dashboard
local function safeRedraw()
    local ok = pcall(redraw)
    if not ok then
        -- look everything up again, it is tried again at the next refresh
        pcall(function() monitors = setupMonitors() end)
        reactor = nil
    end
end

print("Thorium dashboard started with " .. #monitors .. " monitor(s). Hold Ctrl+T to stop.")
safeRedraw()
local timer = os.startTimer(CONFIG.refresh)
while true do
    local ev, a, b, d = os.pullEvent()
    if ev == "timer" and a == timer then
        safeRedraw()
        timer = os.startTimer(CONFIG.refresh)   -- always started again, also after an error
    elseif ev == "monitor_touch" then
        touch(a, b, d)
        safeRedraw()
    elseif ev == "peripheral" or ev == "peripheral_detach" then
        pcall(function() monitors = setupMonitors() end)
        reactor = nil
        safeRedraw()
    elseif ev == "thorium_scram" or ev == "thorium_turbine_warning" then
        safeRedraw()   -- show alarms immediately
    end
end
