import { ToastType, type Toast } from "$lib/toast";
import { writable, type Writable } from "svelte/store";

export const toasts: Writable<Toast[]> = writable([]);

export const addToast = (toast: Toast) => {
  // Create a unique ID so we can easily find/remove it
  // if it is dismissible/has a timeout.
  toast.id = Math.floor(Math.random() * 10000);

  // Setup some sensible defaults for a toast.
  const defaults = {
    id: toast.id,
    type: ToastType.Info,
    dismissible: true,
    timeout: 3000,
  };

  // Push the toast to the top of the list of toasts
  toasts.update((all) => [{ ...defaults, ...toast }, ...all]);

  // If toast is dismissible, dismiss it after "timeout" amount of time.
  if (toast.timeout) setTimeout(() => dismissToast(toast.id), toast.timeout);
};

export const dismissToast = (id: number) => {
  toasts.update((all) => all.filter((t) => t.id !== id));
};