const fields = {
  connectionState: document.getElementById("connection-state"),
  stateDot: document.getElementById("state-dot"),
  robotName: document.getElementById("robot-name"),
  speedRatio: document.getElementById("speed-ratio"),
  motionState: document.getElementById("motion-state"),
  serverVersion: document.getElementById("server-version"),
  clientVersion: document.getElementById("client-version"),
  setupState: document.getElementById("setup-state"),
  enabledState: document.getElementById("enabled-state"),
  j519Status: document.getElementById("j519-status"),
  j519Sequence: document.getElementById("j519-sequence"),
  capturedAt: document.getElementById("captured-at"),
  dof: document.getElementById("dof"),
  joints: document.getElementById("joints"),
  pose: document.getElementById("pose"),
  trajectories: document.getElementById("trajectories"),
  refresh: document.getElementById("refresh")
};

function formatArray(values) {
  if (!Array.isArray(values) || values.length === 0) {
    return "--";
  }

  return values.map(value => Number(value).toFixed(4)).join(", ");
}

function formatNullableBool(value) {
  if (value === true) {
    return "是";
  }

  if (value === false) {
    return "否";
  }

  return "--";
}

function formatJ519Status(snapshot) {
  if (snapshot.j519Status === null || snapshot.j519Status === undefined) {
    return "--";
  }

  const status = Number(snapshot.j519Status).toString(16).padStart(2, "0").toUpperCase();
  return `0x${status} accept=${formatNullableBool(snapshot.j519AcceptsCommand)} received=${formatNullableBool(snapshot.j519ReceivedCommand)} sysrdy=${formatNullableBool(snapshot.j519SystemReady)} motion=${formatNullableBool(snapshot.j519RobotInMotion)}`;
}

function setDot(connectionState) {
  fields.stateDot.className = "dot";
  if (connectionState === "Connected") {
    fields.stateDot.classList.add("good");
  } else if (connectionState === "NotConfigured") {
    fields.stateDot.classList.add("bad");
  }
}

async function refreshStatus() {
  fields.refresh.disabled = true;
  try {
    const response = await fetch("/api/status/snapshot", { cache: "no-store" });
    const payload = await response.json();
    const snapshot = payload.snapshot;

    fields.connectionState.textContent = snapshot.connectionState;
    fields.robotName.textContent = payload.robotName || "--";
    fields.speedRatio.textContent = Number(snapshot.speedRatio).toFixed(2);
    fields.motionState.textContent = snapshot.isInMotion ? "是" : "否";
    fields.serverVersion.textContent = payload.serverVersion;
    fields.clientVersion.textContent = payload.clientVersion;
    fields.setupState.textContent = payload.isSetup ? "是" : "否";
    fields.enabledState.textContent = snapshot.isEnabled ? "是" : "否";
    fields.j519Status.textContent = formatJ519Status(snapshot);
    fields.j519Sequence.textContent = snapshot.j519Sequence ?? "--";
    fields.capturedAt.textContent = new Date(snapshot.capturedAt).toLocaleString();
    fields.dof.textContent = payload.degreesOfFreedom;
    fields.joints.textContent = formatArray(snapshot.jointPositions);
    fields.pose.textContent = formatArray(snapshot.cartesianPose);
    fields.trajectories.textContent = payload.uploadedTrajectories.length > 0
      ? payload.uploadedTrajectories.join(", ")
      : "--";
    fields.trajectories.classList.toggle("empty", payload.uploadedTrajectories.length === 0);
    setDot(snapshot.connectionState);
  } finally {
    fields.refresh.disabled = false;
  }
}

fields.refresh.addEventListener("click", refreshStatus);
refreshStatus();
window.setInterval(refreshStatus, 2000);
