"use strict";

exports.__esModule = true;
exports.useCountDown = useCountDown;

var _vue = require("vue");

var _utils = require("../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);
}

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

  var pause = function pause() {
    counting = false;
    (0, _utils.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 = (0, _utils.raf)(function () {
      // in case of call reset immediately after finish
      if (counting) {
        setRemain(getCurrentRemain());

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

  var macroTick = function macroTick() {
    rafId = (0, _utils.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;
  };

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