-- vi: ft=lua

--import utils for lamp rednet stuffs
require("git-scripts.utils")

--regulate in between these in normal operation
NORMAL_THRESHOLD_U = 8000000
NORMAL_THRESHOLD_L = 7000000
--control rod pos for normal operation
NORMAL_ROD_POS = 81

--proportionally increase production when energy
--storage drops below this level
--(by removing control rods)
HIGH_THRESHOLD = 6000000


local active = false
local ctrl_rods = NORMAL_ROD_POS

local reactor = peripheral.wrap("back")
local mon = peripheral.wrap("right")

--connect to lamp via rednet (if present)
local modemSide = utils.getSideOf("modem")
if modemSide then --not nil
    rednet.open(modemSide)
    lampID = rednet.lookup("reactLamp", "reactLamp")
end

print("Monitoring reactor...")

while (true)
do
    --setup monitor
    mon.clear()

    --get reactor energy
    local energy = reactor.getEnergyStored()
    --display
    mon.setCursorPos(1, 1) --why is there no print() ???
    mon.write(energy)
    mon.write("RF")

        
    if (energy > NORMAL_THRESHOLD_U)
    then
        active = false
    else
        if (energy < NORMAL_THRESHOLD_L)
        then
            active = true
            if (energy < HIGH_THRESHOLD)
            then
                --proportional control
                ctrl_rods = NORMAL_ROD_POS * (energy / HIGH_THRESHOLD)
            end
        end
    end
    
    --actually set state
    mon.setCursorPos(1, 2)
    if (active) 
    then
        reactor.setActive(true)
        mon.write("On")
    else
        reactor.setActive(false)
        mon.write("Off")
    end
    
    mon.setCursorPos(1, 4)
    reactor.setAllControlRodLevels(ctrl_rods)
    mon.write(ctrl_rods)
    mon.write("%")


    --display power produced
    mon.setCursorPos(1, 3)
    mon.write(math.floor(reactor.getEnergyProducedLastTick()))
    mon.write("RF/t")
    

    --also check if fuel has run out
    --(if the fuel inside the reactor isn't
    --getting refilled anymore)
    
    local deltaFuel = reactor.getFuelAmountMax() - reactor.getFuelAmount()
    if (deltaFuel > 2000) --more than 2 buckets (1 for core possibly not being full, another for waste)
    then
        mon.setCursorPos(1, 5)
        mon.write("REFUEL!")

        --send fuel state to lamp
        if lampID then --not nil: rednet present and found lamp!
            rednet.send(lampID, "1", "reactLamp")
        end
    else
        if lampID then
            rednet.send(lampID, "0", "reactLamp")
        end
    end

    sleep(1)
end

--infinite loop; rednet never gets closed