local monitor = peripheral.find("monitor")
local reactor = peripheral.find("fissionReactorLogicAdapter")

if not monitor then error("Monitor not found!") end
if not reactor then error("Reactor adapter not found!") end

monitor.setTextScale(1)

local message = "Ready"

local function percent(value)
    return math.floor(value * 100 + 0.5) .. "%"
end

local function canStart()
    if reactor.getTemperature() >= 600 then
        return false, "Temperature too high"
    end

    if reactor.getDamagePercent() > 0 then
        return false, "Reactor has damage"
    end

    if reactor.getCoolantFilledPercentage() < 0.95 then
        return false, "Low coolant"
    end

    if reactor.getHeatedCoolantFilledPercentage() >= 0.90 then
        return false, "Hot coolant tank high"
    end

    if reactor.getWasteFilledPercentage() >= 0.90 then
        return false, "Waste tank almost full"
    end

    return true, "OK"
end

local function draw()
    monitor.clear()
    local w, h = monitor.getSize()

    local function line(y, text, color)
        if y > h - 2 then return end
        monitor.setCursorPos(1, y)
        monitor.setTextColor(color or colors.white)
        monitor.write((text .. string.rep(" ", w)):sub(1, w))
    end

    line(1, "FISSION REACTOR", colors.yellow)
    line(2, "Status: " ..
        (reactor.getStatus() and "RUNNING" or "OFF"))
    line(3, "Temperature: " ..
        math.floor(reactor.getTemperature()) .. " K")
    line(4, "Damage: " .. percent(reactor.getDamagePercent()))
    line(5, "Fuel: " .. percent(reactor.getFuelFilledPercentage()))
    line(6, "Coolant: " .. percent(reactor.getCoolantFilledPercentage()))
    line(7, "Hot coolant: " ..
        percent(reactor.getHeatedCoolantFilledPercentage()))
    line(8, "Waste: " .. percent(reactor.getWasteFilledPercentage()))
    line(9, message, colors.yellow)

    monitor.setCursorPos(1, h - 1)
    monitor.setBackgroundColor(colors.green)
    monitor.setTextColor(colors.black)
    monitor.write(("[ START ]" .. string.rep(" ", w)):sub(1, w))

    monitor.setCursorPos(1, h)
    monitor.setBackgroundColor(colors.red)
    monitor.write(("[ SCRAM / STOP ]" .. string.rep(" ", w)):sub(1, w))

    monitor.setBackgroundColor(colors.black)
    monitor.setTextColor(colors.white)
end

draw()
local timer = os.startTimer(1)

while true do
    local event, side, x, y = os.pullEvent()

    if event == "monitor_touch" then
        local _, h = monitor.getSize()

        if y == h - 1 then
            local allowed, reason = canStart()

            if allowed then
                reactor.activate()
                message = "Start command sent"
            else
                message = "Start denied: " .. reason
            end

        elseif y == h then
            reactor.scram()
            message = "SCRAM command sent"
        end

        draw()

    elseif event == "timer" and side == timer then
        draw()
        timer = os.startTimer(1)
    end
end
