import { For, Show } from "solid-js"
import { getWorkerState, getWorkerStats } from "@/saeeol/worker"
import { WorkerCell } from "./worker-cell"

export function WorkerGrid() {
  const state = getWorkerState
  const stats = getWorkerStats
  const cols = () => state().config.gridCols

  const rows = () => {
    const order = state().gridOrder
    const c = cols()
    const result: string[][] = []
    for (let i = 0; i < order.length; i += c) {
      result.push(order.slice(i, i + c))
    }
    while (result.length < state().config.gridRows) {
      result.push([])
    }
    return result
  }

  return (
    <box paddingLeft={1} paddingTop={0} paddingBottom={0} paddingRight={0}>
      <text fg="cyan"><b>Worker Grid</b></text>
      <text fg="gray"> {stats().running}▶ {stats().done}✓ {stats().queued}□</text>
      {"\n"}
      <For each={rows()}>
        {(row) => (
          <box flexDirection="row">
            <For each={row}>
              {(id) => {
                const w = () => state().workers[id]
                return (
                  <Show when={w()}>
                    {(worker) => (
                      <WorkerCell
                        worker={worker()}
                        selected={state().selectedID === id}
                      />
                    )}
                  </Show>
                )
              }}
            </For>
          </box>
        )}
      </For>
    </box>
  )
}
