"use strict";

exports.__esModule = true;
exports.default = PollObject;

var _react = _interopRequireWildcard(require("react"));

var _styles = require("@mui/material/styles");

var _Card = _interopRequireDefault(require("@mui/material/Card"));

var _core = require("@selfcommunity/core");

var _material = require("@mui/material");

var _reactIntl = require("react-intl");

var _List = _interopRequireDefault(require("@mui/material/List"));

var _Choice = _interopRequireDefault(require("./Choice"));

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

var _Errors = require("../../../constants/Errors");

var _classnames = _interopRequireDefault(require("classnames"));

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["className", "feedObject", "pollObject", "disabled", "onChange"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const messages = (0, _reactIntl.defineMessages)({
  showPoll: {
    id: 'ui.feedObject.poll.showPoll',
    defaultMessage: 'ui.feedObject.poll.showPoll'
  },
  hidePoll: {
    id: 'ui.feedObject.poll.hidePoll',
    defaultMessage: 'ui.feedObject.poll.hidePoll'
  },
  expDate: {
    id: 'ui.feedObject.poll.expDate',
    defaultMessage: 'ui.feedObject.poll.expDate'
  },
  voters: {
    id: 'ui.feedObject.poll.voters',
    defaultMessage: 'ui.feedObject.poll.voters'
  },
  votes: {
    id: 'ui.feedObject.poll.votes',
    defaultMessage: 'ui.feedObject.poll.votes'
  }
});
const PREFIX = 'SCPollObject';
const classes = {
  root: `${PREFIX}-root`,
  poll: `${PREFIX}-poll`,
  voters: `${PREFIX}-voters`,
  votes: `${PREFIX}-votes`,
  title: `${PREFIX}-title`,
  expandIcon: `${PREFIX}-expand-icon`,
  collapsedIcon: `${PREFIX}-collapsed-icon`
};
const Root = (0, _styles.styled)(_Card.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  marginTop: theme.spacing(1),
  marginBottom: theme.spacing(1),
  borderTop: `1px solid ${theme.palette.grey['A200']}`,
  borderBottom: `1px solid ${theme.palette.grey['A200']}`,
  boxShadow: 'none',
  '& .MuiCardHeader-root': {
    textAlign: 'center',
    width: '100%',
    maxHeight: '10px'
  },
  [`& .${classes.poll}`]: {
    textAlign: 'center'
  },
  [`& .${classes.voters}`]: {
    display: 'flex',
    margin: theme.spacing(1),
    alignItems: 'center',
    justifyContent: 'center',
    '& .MuiIcon-root': {
      width: '0.7em',
      marginRight: '5px'
    }
  },
  [`& .${classes.votes}`]: {
    display: 'flex',
    margin: theme.spacing(1),
    alignItems: 'center',
    justifyContent: 'center',
    '& .MuiIcon-root': {
      width: '1em',
      marginRight: '5px'
    }
  },
  [`& .${classes.title}`]: {
    textTransform: 'uppercase'
  },
  [`& .${classes.expandIcon}`]: {
    marginBottom: 2,
    marginLeft: -2,
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest
    })
  },
  [`& .${classes.collapsedIcon}`]: {
    transform: 'rotate(180deg)'
  },
  '& .MuiTypography-root': {
    fontSize: '1rem'
  }
}));

function PollObject(inProps) {
  //  PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    className,
    feedObject,
    pollObject,
    disabled
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // INTL


  const intl = (0, _reactIntl.useIntl)(); //STATE

  const [obj, setObj] = (0, _react.useState)(pollObject);
  const [votes, setVotes] = (0, _react.useState)(getVotes());
  const [choices, setChoices] = (0, _react.useState)(pollObject.choices);
  const [isVoting, setIsVoting] = (0, _react.useState)(null);
  const [collapsed, setCollapsed] = (0, _react.useState)(Boolean(feedObject && (feedObject.type === _core.SCFeedObjectTypologyType.DISCUSSION || feedObject.html || feedObject.medias.length))); // CONST

  const multipleChoices = pollObject['multiple_choices'];
  const votable = pollObject['closed'];
  /**
   * Handles choice upvote
   */

  const handleVote = id => {
    if (multipleChoices) {
      setChoices(prevChoices => {
        return prevChoices.map(choice => Object.assign({}, choice, {
          voted: choice.id === id ? true : choice.voted,
          vote_count: choice.id === id ? choice.vote_count + 1 : choice.vote_count
        }));
      });
      setVotes(prevVotes => prevVotes + 1);
    } else {
      let isVoted = false;
      setChoices(prevChoices => {
        return prevChoices.map(choice => {
          isVoted = isVoted || choice.voted;
          return Object.assign({}, choice, {
            voted: choice.id === id ? true : false,
            vote_count: choice.id === id ? choice.vote_count + 1 : choice.vote_count > 0 && choice.voted ? choice.vote_count - 1 : choice.vote_count
          });
        });
      });
      !isVoted && setVotes(prevVotes => prevVotes + 1);
    }
  };
  /**
   * Handles choice unvote
   */


  const handleUnVote = id => {
    setChoices(prevChoices => {
      return prevChoices.map(choice => Object.assign({}, choice, {
        voted: choice.id === id ? false : choice.voted,
        vote_count: choice.id === id && choice.vote_count > 0 ? choice.vote_count - 1 : choice.vote_count
      }));
    });
    setVotes(prevVotes => prevVotes - 1);
  };
  /**
   * Gets total votes
   */


  function getVotes() {
    const choices = pollObject.choices;
    let totalVotes = 0;
    let defaultVotes = 0;

    for (let i = 0; i < choices.length; i++) {
      totalVotes += choices[i].vote_count;
    }

    return totalVotes ? totalVotes : defaultVotes;
  }
  /**
   * Performs poll vote
   */


  function vote(choiceObj) {
    setIsVoting(choiceObj.id);

    _core.http.request({
      url: _core.Endpoints.PollVote.url({
        id: feedObject.id,
        type: feedObject['type']
      }),
      method: _core.Endpoints.PollVote.method,
      data: {
        choice: choiceObj.id
      }
    }).then(res => {
      if (choiceObj.voted) {
        handleUnVote(choiceObj.id);
      } else {
        handleVote(choiceObj.id);
      }

      setIsVoting(null);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  }
  /**
   * Handle toggle collapsed/uncollapsed poll
   */


  const handleToggleCollapsedClick = (0, _react.useMemo)(() => () => {
    setCollapsed(prev => !prev);
  }, [collapsed]);
  /**
   * Renders the poll object
   */

  let objElement = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null);

  if (pollObject) {
    objElement = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.CardHeader, {
      title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
        onClick: handleToggleCollapsedClick,
        "aria-expanded": collapsed,
        endIcon: /*#__PURE__*/_react.default.createElement(_Icon.default, {
          className: (0, _classnames.default)(classes.expandIcon, {
            [classes.collapsedIcon]: collapsed
          })
        }, "arrow_upward")
      }, collapsed ? intl.formatMessage(messages.showPoll) : intl.formatMessage(messages.hidePoll))),
      className: classes.title
    }), /*#__PURE__*/_react.default.createElement(_material.Collapse, {
      in: !collapsed,
      timeout: "auto",
      unmountOnExit: true
    }, /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "body1",
      gutterBottom: true,
      align: 'center'
    }, obj.title), obj.expiration_at && Date.parse(obj.expiration_at) >= new Date().getTime() ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "body2",
      gutterBottom: true,
      align: 'center'
    }, `${intl.formatMessage(messages.expDate)}`, `${intl.formatDate(Date.parse(obj.expiration_at), {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric'
    })}`) : /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "body2",
      gutterBottom: true,
      align: 'center'
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.feedObject.poll.closed",
      defaultMessage: "ui.feedObject.poll.closed"
    })), /*#__PURE__*/_react.default.createElement(_List.default, null, choices.map((choice, index) => /*#__PURE__*/_react.default.createElement(_Choice.default, {
      elevation: 0,
      choiceObj: choice,
      key: index,
      feedObject: disabled ? null : feedObject,
      votes: votes,
      vote: vote,
      isVoting: isVoting,
      votable: votable
    }))), multipleChoices ? /*#__PURE__*/_react.default.createElement("div", {
      className: classes.votes
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "list"), /*#__PURE__*/_react.default.createElement(_material.Typography, null, `${intl.formatMessage(messages.votes, {
      total: votes
    })}`)) : /*#__PURE__*/_react.default.createElement("div", {
      className: classes.voters
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "people_alt"), /*#__PURE__*/_react.default.createElement(_material.Typography, null, `${intl.formatMessage(messages.voters, {
      total: votes
    })}`)))));
  }
  /**
   * Renders root element
   */


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: (0, _classnames.default)(classes.root, className)
  }, rest), objElement);
}