"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePoll = void 0;
var _react = require("react");
var _dayjs = _interopRequireDefault(require("dayjs"));
var _utc = _interopRequireDefault(require("dayjs/plugin/utc"));
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
_dayjs.default.extend(_utc.default);
const usePoll = (pollId, shouldFetch) => {
  const [pollData, setPollData] = (0, _react.useState)(undefined);
  const endDays = (0, _react.useMemo)(() => {
    const now = (0, _dayjs.default)().utc();
    if (pollData !== null && pollData !== void 0 && pollData.closedAt) {
      const endDate = (0, _dayjs.default)(pollData.closedAt);
      const hoursRemaining = endDate.diff(now, 'hour');
      const daysRemaining = Math.ceil(hoursRemaining / 24);
      const dayText = daysRemaining > 1 ? 'days' : 'day';
      return `${daysRemaining} ${dayText}`;
    }
    return null;
  }, [pollData]);
  const isPollClosed = (0, _react.useMemo)(() => {
    if (pollData !== null && pollData !== void 0 && pollData.status) {
      return pollData.status === 'closed';
    }
    return false;
  }, [pollData]);
  const totalVote = (0, _react.useMemo)(() => {
    var _pollData$answers;
    if ((pollData === null || pollData === void 0 || (_pollData$answers = pollData.answers) === null || _pollData$answers === void 0 ? void 0 : _pollData$answers.length) > 0) {
      const total = pollData.answers.reduce((acc, poll) => {
        return acc + poll.voteCount;
      }, 0);
      return total;
    } else {
      return 0;
    }
  }, [pollData]);
  const isAlreadyVoted = (0, _react.useMemo)(() => {
    if (pollData !== null && pollData !== void 0 && pollData.answers) {
      return pollData.answers.some(answer => answer.isVotedByUser);
    }
    return false;
  }, [pollData]);
  (0, _react.useEffect)(() => {
    (async () => {
      try {
        _tsSdkReactNative.PollRepository.getPoll(pollId, ({
          data
        }) => setPollData(data));
      } catch (error) {
        console.log(error);
      }
    })();
  }, [pollId, shouldFetch]);
  return {
    data: pollData,
    endDays,
    totalVote,
    isPollClosed,
    isAlreadyVoted
  };
};
exports.usePoll = usePoll;
//# sourceMappingURL=usePoll.js.map