export function controlPageStatusText(status = {}) {
  return [
    status.lastAction ?? "-",
    status.runStatus ?? "-",
    status.error ?? "-",
  ].join(" | ");
}

export function createControlPageRefreshState({
  phase,
  statusText,
  view = null,
  renderResult = null,
  error = null,
} = {}) {
  return {
    phase,
    statusText,
    view,
    renderResult,
    error,
  };
}

export function refreshMachineSessionControlPage({
  getControlView,
  statusNode,
  viewNode,
  renderControlView,
} = {}) {
  if (typeof getControlView !== "function") {
    throw new Error("A control view getter is required.");
  }
  if (!statusNode) {
    throw new Error("A control page status node is required.");
  }
  if (!viewNode) {
    throw new Error("A control page view node is required.");
  }
  if (typeof renderControlView !== "function") {
    throw new Error("A control view renderer is required.");
  }

  let view = null;
  try {
    view = getControlView() ?? null;
  } catch (error) {
    const statusText = `refresh failed | - | ${error.message}`;
    statusNode.textContent = statusText;
    viewNode.textContent = "";
    return createControlPageRefreshState({
      phase: "error",
      statusText,
      error: error.message,
    });
  }

  if (!view) {
    const statusText = "waiting for panel";
    statusNode.textContent = statusText;
    viewNode.textContent = "";
    return createControlPageRefreshState({
      phase: "waiting",
      statusText,
    });
  }

  const statusText = controlPageStatusText(view.status);
  statusNode.textContent = statusText;
  try {
    const renderResult = renderControlView(viewNode, view);
    return createControlPageRefreshState({
      phase: "rendered",
      statusText,
      view,
      renderResult,
    });
  } catch (error) {
    const errorStatusText = `refresh failed | - | ${error.message}`;
    statusNode.textContent = errorStatusText;
    viewNode.textContent = "";
    return createControlPageRefreshState({
      phase: "error",
      statusText: errorStatusText,
      view,
      error: error.message,
    });
  }
}
