"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isOriginallyVector = exports.getPrintQuality = exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));
var _styles = require("@material-ui/core/styles");
var _withWidth = _interopRequireDefault(require("@material-ui/core/withWidth"));
var _SelectionToolbox = _interopRequireDefault(require("redhotmagma-graphics-editor/Components/SelectionToolbox/SelectionToolbox"));
var _ReactComponent = _interopRequireDefault(require("../../../../../Shared/PropTypes/ReactComponent"));
var _TextControlbox = _interopRequireDefault(require("../TextControlbox"));
var _ImageControlbox = _interopRequireDefault(require("../ImageControlbox"));
var _CustomFontOverlay = require("./CustomFontOverlay");
var _fontItemUtils = require("./fontItemUtils");
var _Selectors = require("../../../../Reducers/DesignArea/Selectors");
var _isMobileDevice = _interopRequireDefault(require("../../../../../Framework/Helpers/isMobileDevice"));
var _Selectors2 = require("../../../../Reducers/DesignData/Selectors");
var _i18n = require("../../../../../Framework/i18n");
var _Transformers = require("../../Utils/Transformers");
var _reactRedux = require("react-redux");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var styles = function styles(theme) {
  return {
    root: _defineProperty({
      marginTop: theme.spacing(2),
      marginBottom: theme.spacing(2)
    }, theme.orientation.portrait, {
      marginTop: 'auto',
      marginBottom: 0
    }),
    disableTextEditor: {
      userSelect: 'none'
    }
  };
};
var isButtonDisabled = function isButtonDisabled(isBold, isItalic, fontItem, action) {
  return getFontNextState(isBold, isItalic, fontItem.regular, fontItem.bold, fontItem.italic, fontItem.boldItalic, action) === null;
};
var getFontNextState = function getFontNextState(currentBold, currentItalic, regularAvailable, boldAvailable, italicAvailable, boldItalicAvailable, action) {
  var acceptableOutcomes = [];
  if (action === 'bold') {
    acceptableOutcomes.push({
      bold: !currentBold,
      italic: currentItalic
    });
  } else if (action === 'italic') {
    acceptableOutcomes.push({
      bold: currentBold,
      italic: !currentItalic
    });
  }
  acceptableOutcomes.push({
    bold: !currentBold,
    italic: !currentItalic
  });
  var availableAcceptableOutcomes = acceptableOutcomes.filter(function (acceptableOutcome) {
    if (acceptableOutcome.bold) {
      return acceptableOutcome.italic ? boldItalicAvailable : boldAvailable;
    }
    return acceptableOutcome.italic ? italicAvailable : regularAvailable;
  });
  return availableAcceptableOutcomes.length ? availableAcceptableOutcomes[0] : null;
};
var _handleObjectButtonClick = function handleObjectButtonClick(evt, canvas, onMoveUpClick, onMoveDownClick) {
  switch (evt.currentTarget.value) {
    case 'remove':
      {
        canvas.selectedObject.remove();
        break;
      }
    case 'moveUp':
      {
        onMoveUpClick();
        break;
      }
    case 'moveDown':
      {
        onMoveDownClick();
        break;
      }
    case 'alignHorizontalCenter':
      {
        canvas.selectedObject.alignTo(false, 'center');
        break;
      }
    case 'alignVerticalCenter':
      {
        canvas.selectedObject.alignTo('center', false);
        break;
      }
  }
};
var isOriginallyVector = exports.isOriginallyVector = function isOriginallyVector(object) {
  return object && object.type === 'Image' && (0, _Transformers.isOriginalVector)(object.imageData) || false;
};
var isRaster = function isRaster(object) {
  return object && object.type === 'Image' && /\.(jpe?g|png|gif)$/i.test(object.src) || false;
};
var getPrintQuality = exports.getPrintQuality = function getPrintQuality(object) {
  if (!isOriginallyVector(object) && isRaster(object)) {
    if (object.scaling >= 2) {
      return 'poor';
    }
    if (object.scaling > 1) {
      return 'ok';
    }
  }
  return 'great';
};
var DesignerSelectionToolbox = function DesignerSelectionToolbox(props) {
  var classes = props.classes,
    width = props.width,
    openImageEditDialog = props.openImageEditDialog,
    TextControlboxComponent = props.TextControlboxComponent,
    ImageControlboxComponent = props.ImageControlboxComponent,
    CustomFontOverlayComponent = props.CustomFontOverlayComponent,
    colorDisabled = props.colorDisabled,
    fontFamilyList = props.fonts,
    isActiveBulkName = props.isActiveBulkName,
    getTextContent = props.getTextContent,
    isPortraitMode = props.isPortraitMode,
    addCustomFont = props.addCustomFont,
    defaultFont = props.defaultFont,
    loadFonts = props.loadFonts,
    initialColor = props.initialColor,
    autoFocusEditor = props.autoFocusEditor,
    alignVerticalCenterIcon = props.alignVerticalCenterIcon,
    alignHorizontalCenterIcon = props.alignHorizontalCenterIcon,
    moveDownIcon = props.moveDownIcon,
    moveUpIcon = props.moveUpIcon,
    formatAlignLeftIcon = props.formatAlignLeftIcon,
    formatAlignCenterIcon = props.formatAlignCenterIcon,
    formatAlignRightIcon = props.formatAlignRightIcon,
    formatAlignJustifyIcon = props.formatAlignJustifyIcon,
    formatBoldIcon = props.formatBoldIcon,
    formatItalicIcon = props.formatItalicIcon;
  var rteRef = (0, _react.useRef)(null);
  var editorRef = (0, _react.useRef)(null);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    showCustomFontOverlay = _useState2[0],
    toggleCustomFontOverlay = _useState2[1];
  var disableLinebreaks = (0, _reactRedux.useSelector)(function (state) {
    return (0, _Selectors.isOneLineText)(state);
  });
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.root
  }, /*#__PURE__*/_react["default"].createElement(_SelectionToolbox["default"], null, function (_ref) {
    var canvas = _ref.canvas,
      selectedObject = _ref.selectedObject,
      onMoveUpClick = _ref.onMoveUpClick,
      onMoveDownClick = _ref.onMoveDownClick,
      TextTools = _ref.components.TextTools;
    if (selectedObject.type === 'Text') {
      return /*#__PURE__*/_react["default"].createElement(TextTools, {
        selectedObject: selectedObject,
        canvas: canvas,
        fullTextCommandList: ['fontSize', 'fontFamily'],
        withStateProvider: true,
        fontFamilyList: fontFamilyList,
        rteRef: rteRef,
        editorRef: editorRef
      }, function (textToolsRenderObj) {
        var canvas = textToolsRenderObj.canvas,
          selectedObject = textToolsRenderObj.selectedObject,
          textToolsClasses = textToolsRenderObj.classes,
          renderTextEditor = textToolsRenderObj.renderTextEditor,
          onChangeHTML = textToolsRenderObj.onChangeHTML,
          _textToolsRenderObj$t = textToolsRenderObj.textEditorState,
          formatDoc = _textToolsRenderObj$t.formatDoc,
          getStyleValues = _textToolsRenderObj$t.getStyleValues,
          fontFamilyList = textToolsRenderObj.fontFamilyList;
        var _getStyleValues = getStyleValues(),
          isBold = _getStyleValues.isBold,
          isItalic = _getStyleValues.isItalic,
          textAlign = _getStyleValues.textAlign,
          fontSize = _getStyleValues.fontSize;
        var color = (0, _isEmpty["default"])(initialColor) ? (0, _cloneDeep["default"])(getStyleValues().color) : initialColor;
        var editorBackgroundColor = (0, _Selectors2.hasBackgroundColor)(selectedObject.style.colors.length > 0 ? selectedObject.style.colors : [color]) ? '#C4C4C4' : '#FFFFFF';
        var currentFontItem = (0, _fontItemUtils.findCurrentFontItem)(fontFamilyList, selectedObject.fontItem);

        // add custom font item
        var translatedAddCustomFont = (0, _i18n.t)('textControlbox.addCustomFont');
        var addCustomFontItem = {
          name: translatedAddCustomFont,
          value: translatedAddCustomFont
        };
        var fontsList = [].concat(_toConsumableArray(fontFamilyList), [addCustomFontItem]);
        return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(TextControlboxComponent, {
          selectedObject: selectedObject,
          isActiveBulkName: isActiveBulkName,
          boxed: width !== 'xs',
          isPortraitMode: isPortraitMode,
          textValue: selectedObject.content,
          handleChangeText: onChangeHTML,
          fontValue: currentFontItem,
          fonts: fontsList,
          editorBackgroundColor: editorBackgroundColor,
          color: color,
          handleChangeFont: function handleChangeFont(evt) {
            var fontItem = evt.target.value;
            if (fontItem === addCustomFontItem) {
              toggleCustomFontOverlay(true);
              return;
            }
            canvas.selectedObject.fontItem = (0, _fontItemUtils.createFontItemProps)(fontItem);
          },
          minSize: selectedObject.fontSizeMin,
          maxSize: 1000,
          fontSizeValue: parseInt(fontSize),
          onChangeFontSize: function onChangeFontSize(value) {
            return formatDoc('fontSize', "".concat(value, "px"));
          },
          handleButtonClick: function handleButtonClick(evt) {
            var command = evt.currentTarget.value;
            if (command === 'bold' || command === 'italic') {
              var font = currentFontItem;
              var fontNextState = getFontNextState(isBold, isItalic, font.regular, font.bold, font.italic, font.boldItalic, command);
              if (fontNextState === null) {
                return;
              }
              if (fontNextState.bold !== isBold) {
                formatDoc('bold');
              }
              if (fontNextState.italic !== isItalic) {
                formatDoc('italic');
              }
              return;
            }
            formatDoc(command);
          },
          handleObjectButtonClick: function handleObjectButtonClick(evt) {
            _handleObjectButtonClick(evt, canvas, onMoveUpClick, onMoveDownClick);
          },
          flipToBackDisabled: selectedObject.isFirst,
          flipToFrontDisabled: selectedObject.isLast,
          renderEditorComponent: function renderEditorComponent() {
            var textEditorElementProps = {
              onFocus: function onFocus() {
                if ((0, _Selectors.isPlaceholderContent)(selectedObject.content)) {
                  canvas.selectedObject.content = '';
                }
              },
              onBlur: function onBlur() {
                var regex = /<\/span>/;
                if (selectedObject.content.search(regex) === -1) {
                  canvas.selectedObject.remove();
                }
              }
            };
            if (selectedObject.isBulkName) {
              Object.assign(textEditorElementProps, {
                contentEditable: false,
                className: [textToolsClasses.textEditorContent, classes.disableTextEditor].join(' ')
              });
            }
            return renderTextEditor(_objectSpread(_objectSpread({}, textToolsRenderObj), {}, {
              disableLinebreaks: disableLinebreaks,
              autoFocusWhenMounted: autoFocusEditor || !((0, _Selectors.isPlaceholderContent)(selectedObject.content) || (0, _isMobileDevice["default"])()),
              textEditorElementProps: textEditorElementProps,
              onChangeHTML: function onChangeHTML() {
                // call the original function first with all the args
                textToolsRenderObj.onChangeHTML.apply(textToolsRenderObj, arguments);
                // reload the fonts
                loadFonts(canvas.selectedObject);
              }
            }));
          },
          isBold: isBold,
          boldDisabled: isButtonDisabled(isBold, isItalic, currentFontItem, 'bold'),
          isItalic: isItalic,
          italicDisabled: isButtonDisabled(isBold, isItalic, currentFontItem, 'italic'),
          textAlign: textAlign,
          colorDisabled: colorDisabled,
          isBulkName: selectedObject.isBulkName,
          toggleIsBulkName: function toggleIsBulkName() {
            var isBulkName = !selectedObject.isBulkName;
            canvas.selectedObject.isBulkName = isBulkName;
            canvas.selectedObject.content = getTextContent({
              isBulkName: isBulkName
            });
          },
          alignVerticalCenterIcon: alignVerticalCenterIcon,
          alignHorizontalCenterIcon: alignHorizontalCenterIcon,
          moveDownIcon: moveDownIcon,
          moveUpIcon: moveUpIcon,
          formatAlignLeftIcon: formatAlignLeftIcon,
          formatAlignCenterIcon: formatAlignCenterIcon,
          formatAlignRightIcon: formatAlignRightIcon,
          formatAlignJustifyIcon: formatAlignJustifyIcon,
          formatBoldIcon: formatBoldIcon,
          formatItalicIcon: formatItalicIcon
        }), /*#__PURE__*/_react["default"].createElement(CustomFontOverlayComponent, {
          onClose: function onClose() {
            return toggleCustomFontOverlay(false);
          },
          open: showCustomFontOverlay,
          onApply: function onApply(fontName) {
            var fontItem = _objectSpread(_objectSpread({}, defaultFont), {}, {
              customName: fontName,
              isCustomFont: true
            });
            addCustomFont(fontItem);
            canvas.selectedObject.fontItem = (0, _fontItemUtils.createFontItemProps)(fontItem);
            toggleCustomFontOverlay(false);
          }
        }));
      });
    } else if (selectedObject.type === 'Image' || selectedObject.type === 'Group') {
      return /*#__PURE__*/_react["default"].createElement(ImageControlboxComponent, {
        canvas: canvas,
        boxed: width !== 'xs',
        imageData: selectedObject.imageData,
        printQuality: getPrintQuality(selectedObject),
        openImageEditDialog: openImageEditDialog,
        handleObjectButtonClick: function handleObjectButtonClick(evt) {
          _handleObjectButtonClick(evt, canvas, onMoveUpClick, onMoveDownClick);
        },
        flipToBackDisabled: selectedObject.isFirst,
        flipToFrontDisabled: selectedObject.isLast,
        alignVerticalCenterIcon: alignVerticalCenterIcon,
        alignHorizontalCenterIcon: alignHorizontalCenterIcon,
        moveDownIcon: moveDownIcon,
        moveUpIcon: moveUpIcon
      });
    } else {
      // do not show control box for unknown object types
      return null;
    }
  }));
};
DesignerSelectionToolbox.defaultProps = {
  TextControlboxComponent: _TextControlbox["default"],
  ImageControlboxComponent: _ImageControlbox["default"],
  CustomFontOverlayComponent: _CustomFontOverlay.CustomFontOverlay,
  fonts: [],
  colorDisabled: false,
  classes: {},
  width: '',
  isActiveBulkName: false,
  isPortraitMode: false,
  autoFocusEditor: false
};
var _default = exports["default"] = (0, _withWidth["default"])()((0, _styles.withStyles)(styles, {
  name: 'DesignerSelectionToolbox'
})(DesignerSelectionToolbox));