import { Config, State, Observables, SimpleKinematicsSystem } from "./simple_kinematics";
import { Duration } from "../helpers";
import { createSignal, onMount } from "solid-js";
import { ObservableEntry, ObservablesPanel } from "../ui_helpers";
import { Draw } from "../draw";
import { useSimulation } from "../useSimulation";

function entries(obs: Observables): ObservableEntry[] {
  return [
    { type: "header", label: "General" },
    { type: "scalar", label: "Particles", value: obs.particleCount },
  ];
}

function render(
  canvas: HTMLCanvasElement,
  ctx: CanvasRenderingContext2D,
  system: SimpleKinematicsSystem,
) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  const { particleCount } = system.observables;
  const { position } = system.state;

  for (let i = 0; i < particleCount; i++) {
    const radius = 2;
    Draw.particle(ctx, position.x[i], position.y[i], radius, `hsl(30, 100%, 50%)`);
  }
}

export function SimpleKinematicsView(props: { system: SimpleKinematicsSystem }) {

  const [uiState, setUiState] = createSignal<Observables>(structuredClone(props.system.observables));

  let canvasRef!: HTMLCanvasElement;
  let ctx: CanvasRenderingContext2D;

  onMount(() => {
    ctx = canvasRef.getContext("2d")!;
  });

  const { fps, isPlaying, togglePlay } = useSimulation({
    step(dt: Duration) {
      props.system.flow(dt);
    },
    render() {
      props.system.refreshObservables();
      render(canvasRef, ctx, props.system);
    },
    sync() {
      setUiState(structuredClone(props.system.observables));
    },
    isPlaying: true,
  });

  return (
    <div class="app-layout">
      <div class="cell-0"></div>

      {/* === Top Controls === */}
      <div class="cell-1 controls">
        <button class="btn" onClick={togglePlay} style="width: 70px">
          {isPlaying() ? "Pause" : "Play"}
        </button>
        <button class="btn" onClick={props.system.reset} style="width: 70px">
          Reset
        </button>

        <span class="top-stats">
          FPS: {fps()}
        </span>
      </div>

      <div class="cell-2"></div>

      {/* === Reserved for future brushes === */}
      <div class="cell-3 brushes-panel">
      </div>

      {/* === Canvas === */}
      <div class="cell-4 canvas-container">
        <canvas
          ref={canvasRef}
          width={800} height={600}
        />
      </div>

      {/* === Observables === */}
      <div class="cell-5 side-panel">
        <ObservablesPanel data={ entries(uiState()) }  />
      </div>

    </div>
  );
}

