import toastr from "toastr";
import { Option } from "funfix";

toastr.options = {
  toastClass: 'alert',
  "positionClass": "toast-top-center",
  "timeOut": "1200",
  iconClasses: {
    error: 'alert-info',
    info: 'alert-info',
    success: 'alert-info',
    warning: 'alert-info',
  }
}

const toastrError = (string?: string): void => {
  toastr.error(Option.of(string).getOrElse("请稍后再使用"));
};

const toastrMessage = (string?: string): void => {
  toastr.info(Option.of(string).getOrElse("操作成功"));
};

const execSetLoading = async <T> (setLoading: (loading: boolean) => void,
  function1: () => Promise<T>): Promise<T|undefined> => {
  try {
    setLoading(true);
    const r = await function1() as unknown as T;
    setLoading(false);
    return r;
  } catch (e) {
    toastrError(String(e));
    setLoading(false);
    return undefined;
  }
};

const execToastr = async <T> (function1: () => Promise<T>): Promise<T|undefined> => {
  try {
    return await function1() as unknown as T;
  } catch (e) {
    toastrError(String(e));
    return undefined;
  }
};
export { execToastr, toastrMessage, execSetLoading  };

export default async <T> (function1: () => Promise<T>): Promise<T|undefined> => {
  try {
    return await function1() as unknown as T;
  } catch (e) {
    toastrError(String(e));
    return undefined;
  }
};
