-- factoryos.programs.displaytile — monitor-wall segment driver.
-- Hosts service "display.tile.<cfg.tile>"; the compositor pushes blit rows.

local config = require("factoryos.core.config")
local Node   = require("factoryos.net.node")

local cfg = config.loadOr("/factoryos/node.cfg", {})
local tileId = cfg.tile or "t1"

local mon = peripheral.find("monitor")
assert(mon, "displaytile: no monitor attached")
if mon.setTextScale then pcall(mon.setTextScale, cfg.textScale or 0.5) end
mon.setBackgroundColor(colors.black)
mon.clear()

local node = Node.new(cfg)
assert(node:open(), "displaytile: no modem")

-- touch forwarding: this tile shows a rect of the mainframe's canvas, so
-- taps translate to canvas coords (cfg.tileX/tileY = tile origin) and go
-- back to core.ui on the mainframe as real input. A display wall becomes
-- an interactive surface; a maintenance tile is a window you can work in.
node:on("monitor_touch", function(_, x, y)
  local gx = (cfg.tileX or 1) + x - 1
  local gy = (cfg.tileY or 1) + y - 1
  node:spawn(function()
    node:call("core.ui", "touch", { x = gx, y = gy },
      { timeout = 1.5, chan = node.chan.ui, to = cfg.master })
  end, "tile.touch")
end)

node:service("display.tile." .. tileId, {
  ops = {
    blit = { level = "read", fn = function(_, p)
      for _, row in ipairs((p and p.rows) or {}) do
        mon.setCursorPos(row.x or 1, row.y)
        mon.blit(row.txt or "", row.fg or "", row.bg or "")
      end
    end },
    clear = { level = "read", fn = function()
      mon.setBackgroundColor(colors.black); mon.clear()
      return { ok = true }
    end },
  },
})

node:run()
