import { Events } from "@wailsio/runtime";
import { UpdateService } from "../bindings/github.com/Eriyc/rules_wails/examples/wails3_init_updater";

type Snapshot = {
  state: string;
  currentVersion: string;
  channel: string;
  candidate?: {
    version: string;
    notesMarkdown?: string;
  };
  lastError?: {
    message: string;
  };
};

const currentVersionElement = document.getElementById("current-version")! as HTMLDivElement;
const channelElement = document.getElementById("channel")! as HTMLDivElement;
const stateElement = document.getElementById("state")! as HTMLDivElement;
const candidateVersionElement = document.getElementById("candidate-version")! as HTMLDivElement;
const lastErrorElement = document.getElementById("last-error")! as HTMLDivElement;
const releaseNotesElement = document.getElementById("release-notes")! as HTMLDivElement;
const checkButton = document.getElementById("check")! as HTMLButtonElement;
const downloadButton = document.getElementById("download")! as HTMLButtonElement;
const applyButton = document.getElementById("apply")! as HTMLButtonElement;

function render(snapshot: Snapshot) {
  currentVersionElement.innerText = snapshot.currentVersion ?? "unknown";
  channelElement.innerText = snapshot.channel ?? "unknown";
  stateElement.innerText = snapshot.state ?? "idle";
  candidateVersionElement.innerText = snapshot.candidate?.version ?? "none";
  lastErrorElement.innerText = snapshot.lastError?.message ?? "none";
  releaseNotesElement.innerText = snapshot.candidate?.notesMarkdown ?? "No release selected.";
}

async function refreshSnapshot() {
  render((await UpdateService.Snapshot()) as Snapshot);
}

checkButton.addEventListener("click", async () => {
  render((await UpdateService.Check()) as Snapshot);
});

downloadButton.addEventListener("click", async () => {
  render((await UpdateService.Download()) as Snapshot);
});

applyButton.addEventListener("click", async () => {
  try {
    await UpdateService.ApplyAndRestart();
  } catch (error) {
    lastErrorElement.innerText = String(error);
  }
});

Events.On("updates:state", (event) => {
  render(event.data as Snapshot);
});

refreshSnapshot().catch((error) => {
  lastErrorElement.innerText = String(error);
});
