"use strict";

exports.__esModule = true;
exports.default = _default;

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

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

var _Autocomplete = _interopRequireDefault(require("@mui/material/Autocomplete"));

var _TextField = _interopRequireDefault(require("@mui/material/TextField"));

var _CircularProgress = _interopRequireDefault(require("@mui/material/CircularProgress"));

var _Checkbox = _interopRequireDefault(require("@mui/material/Checkbox"));

var _parse = _interopRequireDefault(require("autosuggest-highlight/parse"));

var _match = _interopRequireDefault(require("autosuggest-highlight/match"));

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

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

var _TagChip = _interopRequireDefault(require("../../../shared/TagChip"));

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

const _excluded = ["onChange", "defaultValue", "limitCountTags", "checkboxSelect", "disabled", "TextFieldProps"];

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 PREFIX = 'SCComposerAudience';
const classes = {
  root: `${PREFIX}-root`
};
const Root = (0, _styles.styled)(_Autocomplete.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => ({
  minWidth: 120
}));

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

  const {
    onChange,
    defaultValue = [],
    limitCountTags = 0,
    checkboxSelect = false,
    disabled = false,
    TextFieldProps = {
      variant: 'outlined',
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.composer.audience.tags.label",
        defaultMessage: "ui.composer.audience.tags.label"
      })
    }
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // State


  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [open, setOpen] = (0, _react.useState)(false);
  const [tags, setTags] = (0, _react.useState)([]);
  const [value, setValue] = (0, _react.useState)(defaultValue);

  const load = () => {
    _core.http.request({
      url: _core.Endpoints.ComposerAddressingTagList.url(),
      method: _core.Endpoints.ComposerAddressingTagList.method
    }).then(res => {
      setTags(res.data);
    }).then(() => setIsLoading(false));
  }; // Component update


  (0, _react.useEffect)(() => {
    if (!isLoading && open && tags.length === 0) {
      load();
    }
  }, [open]); // Handlers

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleChange = (event, value) => {
    let newValue = null;

    if (limitCountTags > 0) {
      const [...rest] = value;
      newValue = rest.slice(-1 * limitCountTags);
    } else {
      newValue = value;
    }

    setValue(newValue);
    onChange && onChange(newValue);
  };

  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: classes.root,
    open: open,
    onOpen: handleOpen,
    onClose: handleClose,
    disabled: disabled,
    multiple: true,
    options: tags || [],
    getOptionLabel: option => option.name || '',
    value: value,
    filterSelectedOptions: !checkboxSelect,
    disableCloseOnSelect: checkboxSelect,
    selectOnFocus: true,
    clearOnBlur: true,
    handleHomeEndKeys: true,
    clearIcon: null,
    noOptionsText: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.audience.tags.empty",
      defaultMessage: "ui.composer.audience.tags.empty"
    }),
    onChange: handleChange,
    isOptionEqualToValue: (option, value) => value.id === option.id,
    renderTags: (value, getTagProps) => {
      return value.map((option, index) => /*#__PURE__*/_react.default.createElement(_TagChip.default, _extends({
        key: option.id,
        tag: option
      }, getTagProps({
        index
      }))));
    },
    renderOption: (props, option, {
      selected,
      inputValue
    }) => {
      const matches = (0, _match.default)(option.name, inputValue);
      const parts = (0, _parse.default)(option.name, matches);
      return /*#__PURE__*/_react.default.createElement("li", props, checkboxSelect && /*#__PURE__*/_react.default.createElement(_Checkbox.default, {
        style: {
          marginRight: 8
        },
        checked: selected
      }), /*#__PURE__*/_react.default.createElement(_TagChip.default, {
        key: option.id,
        tag: option,
        label: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, parts.map((part, index) => /*#__PURE__*/_react.default.createElement("span", {
          key: index,
          style: {
            fontWeight: part.highlight ? 700 : 400
          }
        }, part.text)))
      }));
    },
    renderInput: params => {
      return /*#__PURE__*/_react.default.createElement(_TextField.default, _extends({}, params, TextFieldProps, {
        InputProps: Object.assign({}, params.InputProps, {
          autoComplete: 'addressing',
          // disable autocomplete and autofill
          endAdornment: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, isLoading ? /*#__PURE__*/_react.default.createElement(_CircularProgress.default, {
            color: "inherit",
            size: 20
          }) : null, params.InputProps.endAdornment)
        })
      }));
    }
  }, rest));
}