import { is_object_ready } from "../../../../../../ChillDocStoreBundle/Resources/public/vuejs/StoredObjectButton/helpers";
import {
  StoredObject,
  StoredObjectStatus,
  StoredObjectStatusChange,
} from "../../../../../../ChillDocStoreBundle/Resources/public/types";

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 (e) {
  if (undefined === (window as any).stored_object) {
    console.error("window.stored_object is undefined");
    throw Error("window.stored_object is undefined");
  }

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