import { inject, provide, ref } from "vue";
import { head, isUndefined, now, remove } from "lodash-es";
export const AlertKey = Symbol.for("ramacare:alert");
export function createAlert() {
  const items = ref([]);
  provide(AlertKey, {
    addAlert(item) {
      const defaultValues = {
        statusCode: 0,
        statusMessage: "",
        alertLocation: "default",
        alertType: "info",
        alertIcon: "",
        alertDateTime: now(),
        alertExpireIn: 1e3 * 60,
        // 1 minute
        data: {}
      };
      const newItem = { ...defaultValues, ...item };
      if (!isUndefined(newItem.message)) {
        items.value.push(newItem);
      }
    },
    takeAlert(location = "default") {
      const item = head(items.value.filter((i) => i.alertLocation === location));
      if (item) remove(items.value, (i) => i === item);
      return item;
    },
    hasAlert(location = "default") {
      return items.value.some((i) => i.alertLocation === location);
    },
    clear() {
      items.value = [];
    },
    items
  });
  setInterval(() => {
    items.value = items.value.filter((i) => Number(i.alertDateTime) + Number(i.alertExpireIn) > now());
  }, 1e3);
}
export function useAlert() {
  return inject(AlertKey, null);
}
