import { is_object_ready } from "ChillDocStoreAssets/vuejs/StoredObjectButton/helpers";
import { StoredObject } from "ChillDocStoreAssets/types";

declare global {
  interface Window {
    stored_object: string | undefined;
  }
}

async function reload_if_needed(
  stored_object: StoredObject,
  i: number,
): Promise<void> {
  const current_status = await is_object_ready(stored_object);

  if (stored_object.status !== current_status.status) {
    window.location.reload();
  }
  wait_before_reload(stored_object, i + 1);
  return Promise.resolve();
}

function wait_before_reload(stored_object: StoredObject, i: number): void {
  /**
   * value of the timeout. Set to 5 sec during the first 10 minutes, then every 1 minute
   */
  const timeout = i < 1200 ? 5000 : 60000;

  setTimeout(reload_if_needed, timeout, stored_object, i);
}

window.addEventListener("DOMContentLoaded", async function () {
  if (undefined === window.stored_object) {
    console.error("window.stored_object is undefined");
    throw Error("window.stored_object is undefined");
  }

  const stored_object = JSON.parse(window.stored_object) as StoredObject;
  reload_if_needed(stored_object, 0);
});
