"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePoll = void 0;
var _react = require("react");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _toastSlice = require("../../core/stores/slices/toastSlice");
const POLL_ERROR = {
  POLL_CLOSED: 'Poll was closed',
  POLL_NOT_FOUND: 'Poll not found'
};
const usePoll = pollId => {
  const [poll, setPoll] = (0, _react.useState)(undefined);
  const [isAuthorSeeingResults, setIsAuthorSeeingResults] = (0, _react.useState)(false);
  const {
    showToast
  } = (0, _toastSlice.useToast)();
  const [loading, setLoading] = (0, _react.useState)(false);
  const isPollClosed = (0, _react.useMemo)(() => {
    return (poll === null || poll === void 0 ? void 0 : poll.status) === 'closed';
  }, [poll]);
  const isAlreadyVoted = (0, _react.useMemo)(() => {
    return poll === null || poll === void 0 ? void 0 : poll.isVoted;
  }, [poll]);
  const totalVotes = (0, _react.useMemo)(() => {
    var _poll$answers;
    const total = poll === null || poll === void 0 || (_poll$answers = poll.answers) === null || _poll$answers === void 0 ? void 0 : _poll$answers.reduce((acc, answer) => {
      return acc + answer.voteCount;
    }, 0);
    return total;
  }, [poll]);
  (0, _react.useEffect)(() => {
    _tsSdkReactNative.PollRepository.getPoll(pollId, ({
      data,
      loading: pollLoading
    }) => {
      setPoll(data);
      setLoading(pollLoading);
    });
  }, [pollId]);
  const handlePollError = error => {
    var _error$message, _error$message2;
    if (error !== null && error !== void 0 && (_error$message = error.message) !== null && _error$message !== void 0 && _error$message.includes(POLL_ERROR.POLL_CLOSED)) {
      showToast({
        type: 'informative',
        message: 'Poll ended.'
      });
    } else if (error !== null && error !== void 0 && (_error$message2 = error.message) !== null && _error$message2 !== void 0 && _error$message2.includes(POLL_ERROR.POLL_NOT_FOUND)) {
      showToast({
        type: 'informative',
        message: 'This poll is no longer available.'
      });
    } else {
      showToast({
        type: 'failed',
        message: 'Oops, something went wrong.'
      });
    }
  };
  const votePoll = async answerIds => {
    try {
      await _tsSdkReactNative.PollRepository.votePoll(pollId, answerIds);
    } catch (error) {
      handlePollError(error);
    }
  };
  const unvotePoll = async () => {
    try {
      await _tsSdkReactNative.PollRepository.unvotePoll(pollId);
      showToast({
        type: 'success',
        message: 'Vote removed.'
      });
    } catch (error) {
      handlePollError(error);
    }
  };
  return {
    poll,
    loading,
    votePoll,
    unvotePoll,
    totalVotes,
    isPollClosed,
    isAlreadyVoted,
    isAuthorSeeingResults,
    setIsAuthorSeeingResults
  };
};
exports.usePoll = usePoll;
//# sourceMappingURL=usePoll.js.map