import { ref, computed, onActivated, onDeactivated, onBeforeUnmount } from 'vue';
import { raf, cancelRaf } from '../utils';
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;

function parseTime(time) {
  var days = Math.floor(time / DAY);
  var hours = Math.floor(time % DAY / HOUR);
  var minutes = Math.floor(time % HOUR / MINUTE);
  var seconds = Math.floor(time % MINUTE / SECOND);
  var milliseconds = Math.floor(time % SECOND);
  return {
    total: time,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    milliseconds: milliseconds
  };
}

function isSameSecond(time1, time2) {
  return Math.floor(time1 / 1000) === Math.floor(time2 / 1000);
}

export function useCountDown(options) {
  var rafId;
  var endTime;
  var counting;
  var deactivated;
  var remain = ref(options.time);
  var current = computed(function () {
    return parseTime(remain.value);
  });

  var pause = function pause() {
    counting = false;
    cancelRaf(rafId);
  };

  var getCurrentRemain = function getCurrentRemain() {
    return Math.max(endTime - Date.now(), 0);
  };

  var setRemain = function setRemain(value) {
    remain.value = value;
    options.onChange == null ? void 0 : options.onChange(current.value);

    if (value === 0) {
      pause();
      options.onFinish == null ? void 0 : options.onFinish();
    }
  };

  var microTick = function microTick() {
    rafId = raf(function () {
      // in case of call reset immediately after finish
      if (counting) {
        setRemain(getCurrentRemain());

        if (remain.value > 0) {
          microTick();
        }
      }
    });
  };

  var macroTick = function macroTick() {
    rafId = raf(function () {
      // in case of call reset immediately after finish
      if (counting) {
        var remainRemain = getCurrentRemain();

        if (!isSameSecond(remainRemain, remain.value) || remainRemain === 0) {
          setRemain(remainRemain);
        }

        if (remain.value > 0) {
          macroTick();
        }
      }
    });
  };

  var tick = function tick() {
    if (options.millisecond) {
      microTick();
    } else {
      macroTick();
    }
  };

  var start = function start() {
    if (!counting) {
      endTime = Date.now() + remain.value;
      counting = true;
      tick();
    }
  };

  var reset = function reset(totalTime) {
    if (totalTime === void 0) {
      totalTime = options.time;
    }

    pause();
    remain.value = totalTime;
  };

  onBeforeUnmount(pause);
  onActivated(function () {
    if (deactivated) {
      counting = true;
      deactivated = false;
      tick();
    }
  });
  onDeactivated(function () {
    if (counting) {
      pause();
      deactivated = true;
    }
  });
  return {
    start: start,
    pause: pause,
    reset: reset,
    current: current
  };
}