import { useEffect } from 'react';

type TimeOptions = {
  tag?: string;
  interval?: number;
  callback?: (() => Promise<void>) | ((deps: readonly any[]) => Promise<void>);
  fireAtFirst?: boolean;
  enabled?: boolean;
  printInfo?: boolean;
};

function useTimer(set: TimeOptions, deps?: readonly any[]): void {
  const localdeps = deps ? deps : [];

  const printInfoF = (info: string) => {
    if (set.printInfo) {
      console.info(info);
    }
  };

  useEffect(() => {
    if (set.enabled === false) {
      printInfoF(`timer ${set.tag} disabled.`);
      return () => {};
    }
    if (!set.callback) {
      return () => {};
    }
    printInfoF(`timer ${set.tag} enabled.`);
    const callBack = () => {
      if (set.callback) {
        (set.callback as (deps: readonly any[]) => Promise<void>)(deps ? deps : []).finally(() => {
          printInfoF(`timer ${set.tag} elapsed at ${new Date().toUTCString()}.`);
        });
      }
    };

    if (set.fireAtFirst) {
      callBack();
    }

    const t = setInterval(callBack, set.interval || 1000);
    return () => {
      clearTimeout(t);
    };
  }, [set, ...localdeps]);
}

export { TimeOptions };
export default useTimer;
