"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UpvoteButtonForFeed = UpvoteButtonForFeed;
exports["default"] = void 0;

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

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

var _firework = _interopRequireDefault(require("../firework"));

var _selector = _interopRequireDefault(require("./selector"));

var _attitude = _interopRequireDefault(require("./attitude"));

var _requestApis = require("./request-apis");

var _upvoteListModal = _interopRequireDefault(require("./upvoteListModal"));

var _tooltip = _interopRequireDefault(require("../tooltip"));

var _getLocale = require("../../utils/getLocale");

require("./index.css");

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 _getRequireWildcardCache(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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var getBackgroundImage = function getBackgroundImage(type) {
  var selected = (0, _attitude["default"])().find(function (a) {
    return a.type == type;
  });

  if (selected) {
    return {
      backgroundImage: "url(".concat(selected.img, ")")
    };
  }

  return {};
};

function UpvoteButton(_ref) {
  var _classnames;

  var type = _ref.type,
      count = _ref.count,
      style = _ref.style,
      feedId = _ref.feedId,
      renderCount = _ref.renderCount,
      renderBuntton = _ref.renderBuntton,
      onChange = _ref.onChange,
      handleRequest = _ref.handleRequest,
      _ref$popAlign = _ref.popAlign,
      popAlign = _ref$popAlign === void 0 ? "right" : _ref$popAlign,
      _ref$buttonType = _ref.buttonType,
      buttonType = _ref$buttonType === void 0 ? "" : _ref$buttonType,
      _ref$customUpvoteBtnC = _ref.customUpvoteBtnCls,
      customUpvoteBtnCls = _ref$customUpvoteBtnC === void 0 ? "" : _ref$customUpvoteBtnC,
      getPopupContainer = _ref.getPopupContainer;

  var _useState = (0, _react.useState)({
    type: type,
    count: count
  }),
      _useState2 = _slicedToArray(_useState, 2),
      upvoteState = _useState2[0],
      setUpvoteState = _useState2[1];

  var btnref = (0, _react.useRef)();

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      modalVisible = _useState4[0],
      setModalVisible = _useState4[1];

  var wrapperRef = (0, _react.useRef)(document.createElement('div'));
  (0, _react.useEffect)(function () {
    setUpvoteState({
      type: type,
      count: count
    });
  }, [count, type]);
  var setFirework = (0, _react.useCallback)(function () {
    var _getBoundingClientRec = btnref.current.getBoundingClientRect(),
        x = _getBoundingClientRec.x,
        y = _getBoundingClientRec.y;

    (0, _firework["default"])({
      x: x,
      y: y,
      images: (0, _attitude["default"])().map(function (a) {
        return a.img;
      })
    });
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "feed-upvote pull-screen-click-through pull-screen-ignore",
    style: style,
    ref: wrapperRef
  }, /*#__PURE__*/_react["default"].createElement(_selector["default"], {
    getPopupContainer: function getPopupContainer() {
      return wrapperRef.current || document.body;
    } // visible={selectorVisible}
    ,
    align: popAlign,
    onSelect: /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(type) {
        var count;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                count = upvoteState.type ? upvoteState.count : upvoteState.count + 1;
                setUpvoteState({
                  type: type,
                  count: count
                });
                setFirework();

                if (!handleRequest) {
                  _context.next = 8;
                  break;
                }

                _context.next = 6;
                return handleRequest(type);

              case 6:
                _context.next = 10;
                break;

              case 8:
                _context.next = 10;
                return (0, _requestApis.praise)(feedId, type);

              case 10:
                onChange && onChange(type, count);

              case 11:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function (_x) {
        return _ref2.apply(this, arguments);
      };
    }()
  }, /*#__PURE__*/_react["default"].createElement("a", {
    className: "feed-upvote-button__wrapper",
    onClick: /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(upvoteState.type != 0)) {
                _context2.next = 11;
                break;
              }

              setUpvoteState({
                type: 0,
                count: upvoteState.count - 1
              });

              if (!handleRequest) {
                _context2.next = 7;
                break;
              }

              _context2.next = 5;
              return handleRequest(0);

            case 5:
              _context2.next = 9;
              break;

            case 7:
              _context2.next = 9;
              return (0, _requestApis.cancelPraise)(feedId);

            case 9:
              onChange && onChange(0, upvoteState.count - 1);
              return _context2.abrupt("return");

            case 11:
              setFirework();
              setUpvoteState({
                type: 1,
                count: upvoteState.count + 1
              });

              if (!handleRequest) {
                _context2.next = 18;
                break;
              }

              _context2.next = 16;
              return handleRequest(1);

            case 16:
              _context2.next = 20;
              break;

            case 18:
              _context2.next = 20;
              return (0, _requestApis.praise)(feedId, 1);

            case 20:
              onChange && onChange(1, upvoteState.count + 1);

            case 21:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    })),
    ref: btnref
  }, renderBuntton ? renderBuntton(upvoteState.type, upvoteState.count) : /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])((_classnames = {
      "tu-icon-APP-zan1": !buttonType && upvoteState.type == 0
    }, _defineProperty(_classnames, customUpvoteBtnCls, customUpvoteBtnCls && upvoteState.type == 0), _defineProperty(_classnames, buttonType, buttonType && upvoteState.type == 0), _defineProperty(_classnames, "feed-upvote-button", true), _classnames)),
    style: getBackgroundImage(upvoteState.type)
  }))), /*#__PURE__*/_react["default"].createElement("a", {
    className: "feed-upvote-count",
    onClick: function onClick() {
      upvoteState.count > 0 && setModalVisible(true);
    }
  }, /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
    overlay: (0, _getLocale.getLocale)("Tasks_Tab_MyS_Kudosrec"),
    placement: "top"
  }, /*#__PURE__*/_react["default"].createElement("span", null, renderCount ? renderCount(upvoteState.type, upvoteState.count) : upvoteState.count))), /*#__PURE__*/_react["default"].createElement(_upvoteListModal["default"], {
    feedId: feedId,
    visible: modalVisible,
    onClose: function onClose() {
      return setModalVisible(false);
    }
  }));
}

function UpvoteButtonForFeed(props) {
  return /*#__PURE__*/_react["default"].createElement(UpvoteButton, _extends({}, props, {
    renderBuntton: function renderBuntton(type) {
      var text = !type ? (0, _getLocale.getLocale)("Mod_Kudos") : (0, _getLocale.getLocale)("Mod_Alreadyliked");
      return /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          display: "flex",
          alignItems: "center"
        }
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames2["default"])({
          "tu-icon-APP-zan1": type == 0,
          "feed-upvote-button": true
        }),
        style: _objectSpread(_objectSpread({}, getBackgroundImage(type)), {}, {
          marginRight: 4
        })
      }), text);
    },
    renderCount: function renderCount(type, count) {
      return count || null;
    }
  }));
}

UpvoteButton.getAttitudes = function () {
  return (0, _attitude["default"])().map(function (att) {
    return _objectSpread({}, att);
  });
};

UpvoteButton.ForFeed = UpvoteButtonForFeed;
var _default = UpvoteButton;
exports["default"] = _default;