-- FF_STORY_COMPUTER_GUARD
local function ff_story_computer_allowed()
  local label = os.getComputerLabel and os.getComputerLabel() or nil
  return fs.exists(".ff_story_computer")
    or fs.exists(".ff_titan_computer")
    or fs.exists(".ff_titan_program_id")
    or fs.exists(".ff_titan_allow_autoinstall")
    or fs.exists(".ff_titan_allow_autorun")
    or (label ~= nil and string.sub(string.lower(label), 1, 9) == "ff_titan:")
end

if not ff_story_computer_allowed() then
  return
end
-- TITAN RED LEVEL
-- DECONTAMINATION CONTROL TERMINAL
-- Save as: startup
--
-- Output:
-- back = decontamination start signal
--
-- Intended wiring:
-- Computer back output -> redstone lamp at -495 72 -208

local OUTPUT_SIDE = "back"
local STATE_FILE = ".red_decontamination_started"

local function hasColor()
  return term.isColor and term.isColor()
end

local function c(col)
  if hasColor() then term.setTextColor(col) end
end

local function cls()
  term.setBackgroundColor(colors.black)
  term.clear()
  term.setCursorPos(1, 1)
end

local function writeLine(text, col)
  c(col or colors.white)
  print(text)
end

local function readClean()
  c(colors.white)
  write("> ")
  local s = read() or ""
  s = string.upper(s)
  s = string.gsub(s, "^%s+", "")
  s = string.gsub(s, "%s+$", "")
  return s
end

local function pause()
  c(colors.gray)
  print("")
  print("[key] back")
  os.pullEvent("key")
end

local function header(title)
  cls()
  c(colors.lime)
  print("DECONTAMINATION CONTROL")
  c(colors.gray)
  print("RED LEVEL LOCAL TERMINAL")
  print("---------------------------------------")
  if title then
    c(colors.white)
    print(title)
    c(colors.gray)
    print("---------------------------------------")
  end
  c(colors.white)
end

local function started()
  return fs.exists(STATE_FILE)
end

local function saveStarted()
  local f = fs.open(STATE_FILE, "w")
  f.write("DECONTAMINATION STARTED")
  f.close()
end

local function setOutput(on)
  redstone.setOutput(OUTPUT_SIDE, on)
end

local function bootOutput()
  setOutput(started())
end

local function draw(lines)
  for _, line in ipairs(lines) do
    if string.find(line, "ACTIVE") or string.find(line, "READY") or string.find(line, "START") then
      writeLine(line, colors.lime)
    elseif string.find(line, "LEAVE") or string.find(line, "DEATH") or string.find(line, "RED LEVEL") then
      writeLine(line, colors.red)
    elseif string.find(line, "BIOCHECK") or string.find(line, "WHITE CIRCLE") or string.find(line, "SCAN") then
      writeLine(line, colors.cyan)
    elseif string.find(line, "LOCAL") or string.find(line, "NOTE") then
      writeLine(line, colors.orange)
    else
      writeLine(line, colors.white)
    end
  end
end

local function page(title, lines)
  header(title)
  draw(lines)
  pause()
end

local function status()
  if started() then
    page("STATUS", {
      "DECONTAMINATION: ACTIVE",
      "",
      "The start signal has been sent.",
      "",
      "Follow the white circles."
    })
  else
    page("STATUS", {
      "DECONTAMINATION: READY",
      "",
      "This terminal starts the purge route.",
      "",
      "It will not wait after activation.",
      "",
      "Read the route note first."
    })
  end
end

local function routeNote()
  page("ROUTE NOTE", {
    "BIOCHECK ROUTE",
    "",
    "The bio-scan order is fixed.",
    "",
    "1. Maintenance Shaft",
    "2. Growth Hall",
    "3. Storage Lobby",
    "4. Mutation Observation Wing",
    "5. Subject Testing Sectors",
    "",
    "Stand inside each WHITE CIRCLE",
    "until the scan clears."
  })
end

local function safetyNote()
  page("SAFETY NOTE", {
    "LOCAL NOTICE",
    "",
    "After the final scan, leave RED LEVEL.",
    "",
    "If it breathes, it is treated",
    "as contamination.",
    "",
    "Use the elevator."
  })
end

local function oldMemo()
  page("OLD MEMO", {
    "RECOVERED PAPER COPY",
    "",
    "Do not start decon from the hallway.",
    "",
    "The first scan point is close enough",
    "to reach from this room."
  })
end

local function startDecon()
  if started() then
    page("START", {
      "Already active.",
      "",
      "The signal is still ON.",
      "",
      "Move to the current scan point."
    })
    return
  end

  header("START")

  draw({
    "Start decontamination sequence?",
    "",
    "This will activate the scan route.",
    "",
    "White circles will appear in order.",
    "",
    "After the route completes,",
    "RED LEVEL will be decontaminated.",
    "",
    "Type START to begin."
  })

  print("")
  local got = readClean()

  if got ~= "START" then
    page("CANCELLED", {
      "No signal sent.",
      "",
      "Route remains inactive."
    })
    return
  end

  saveStarted()
  setOutput(true)

  page("ACTIVE", {
    "DECONTAMINATION STARTED",
    "",
    "Signal sent.",
    "",
    "Go to the first WHITE CIRCLE.",
    "",
    "BIOCHECK 01:",
    "Maintenance Shaft"
  })
end

bootOutput()

while true do
  header()

  if started() then
    writeLine("DECONTAMINATION: ACTIVE", colors.lime)
  else
    writeLine("DECONTAMINATION: READY", colors.orange)
  end

  print("")
  writeLine("1. Status")
  writeLine("2. Route note")
  writeLine("3. Safety note")
  writeLine("4. Old memo")
  writeLine("S. START")
  writeLine("Q. Close")
  print("")

  local input = readClean()

  if input == "Q" or input == "QUIT" or input == "EXIT" then
    cls()
    writeLine("SESSION CLOSED", colors.gray)
    return
  elseif input == "1" then
    status()
  elseif input == "2" then
    routeNote()
  elseif input == "3" then
    safetyNote()
  elseif input == "4" then
    oldMemo()
  elseif input == "S" or input == "START" then
    startDecon()
  else
    c(colors.red)
    print("Invalid.")
    sleep(0.7)
  end
end