import { getCurrentInstance } from 'vue';
import type { Response } from '../models/Response';
import { AxiosError } from 'axios';

export function useNotify() {
  const instance = getCurrentInstance();
  const $q = instance?.appContext.config.globalProperties.$q;

  function NotifyResponse(
    response: Response | string | AxiosError | undefined,
    type?: 'warning' | 'error',
    timeout: number = 5000,
  ) {
    let color = 'green';
    let icon = 'check_circle';

    switch (type) {
      case 'warning':
        color = 'orange';
        icon = 'warning';
        break;
      case 'error':
        color = 'red';
        icon = 'error';
        break;
    }

    if (response) {
      let message = '';
      if (response instanceof AxiosError && response.response) {
        if (response.response.data) {
          const data = response.response.data as Response;
          message = data.message;
        }
      } else {
        message = typeof response === 'string' ? response : (response.message ?? '');
      }
      if (message === '') {
        return;
      }

      color = typeof response === 'string' ? color : type === 'error' ? 'red' : color;
      icon = typeof response === 'string' ? icon : type === 'error' ? 'error' : icon;
      if (!$q) {
        console.error(message);
        return;
      }
      $q?.notify({
        message: message,
        color: color,
        position: 'bottom-right',
        icon: icon,
        timeout: timeout,
      });
    }
  }

  function NotifyDialog(title: string, text: string, okText?: string, cancelText?: string) {
    return new Promise((resolve) => {
      $q
        ?.dialog({
          title: title,
          message: text,
          persistent: true,
          ok: okText ?? 'OK',
          cancel: cancelText ?? 'CANCEL',
        })
        .onOk(() => {
          resolve(true);
        })
        .onCancel(() => {
          resolve(false);
        })
        .onDismiss(() => {
          resolve(false);
        });
    });
  }
  return {
    NotifyDialog,
    NotifyResponse,
  };
}
