import { nextTick, type UnwrapRef } from "vue";
import { APIError } from "./api_error";

export function objForEach<T>(obj: T, f: (k: keyof T, v: T[keyof T]) => void): void {
  for (const k in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, k)) {
      f(k, obj[k]);
    }
  }
}

export type VueLike<T> = T | UnwrapRef<T>;

export function unwrap_vuelike<T>(value: VueLike<T>): T {
  return value as T;
}

export type Loading<T> = T | "loading" | "error";

export function unwrap_loading<T>(o: Loading<T>): T {
  if (o === "loading" || o === "error") throw null;

  return o;
}

export function wait_for(condition: () => boolean, action: () => void): void {
  const enqueue_action = () => {
    if (!condition()) {
      nextTick(enqueue_action);
      return;
    }

    action();
  };
  enqueue_action();
}

export function handle_error(error: unknown): void {
  if (error instanceof APIError) {
    error.alert();
  } else {
    console.error(error);
  }
}

export function name_door(day: number): string {
  return `Türchen ${day}`;
}
