"use strict";

exports.__esModule = true;
exports.CutsiteFilter = CutsiteFilter;
exports["default"] = void 0;
var _reactRedux = require("react-redux");
var _redux = require("redux");
var _core = require("@blueprintjs/core");
var _withEditorProps = _interopRequireDefault(require("../withEditorProps"));
var _specialCutsiteFilterOptions = _interopRequireDefault(require("../constants/specialCutsiteFilterOptions"));
var _react = _interopRequireWildcard(require("react"));
require("./style.css");
var _teselagenReactComponents = require("teselagen-react-components");
var _lodash = require("lodash");
var _GlobalDialogUtils = require("../GlobalDialogUtils");
var _AdditionalCutsiteInfoDialog = require("./AdditionalCutsiteInfoDialog");
var _withRestrictionEnzymes = require("./withRestrictionEnzymes");
var _sequenceUtils = require("@teselagen/sequence-utils");
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
var NoResults = (0, _withRestrictionEnzymes.withRestrictionEnzymes)(function (props) {
  var inputSequenceToTestAgainst = props.inputSequenceToTestAgainst,
    cutsitesByName = props.cutsitesByName,
    cutsitesByNameActive = props.cutsitesByNameActive,
    closeDropDown = props.closeDropDown,
    allRestrictionEnzymes = props.allRestrictionEnzymes,
    _props$queryString = props.queryString,
    queryString = _props$queryString === void 0 ? "" : _props$queryString,
    onHiddenEnzymeAdd = props.onHiddenEnzymeAdd,
    manageEnzymesLink = props.manageEnzymesLink;
  var enzymesByNameThatMatch = (0, _lodash.pickBy)(allRestrictionEnzymes, function (v, k) {
    if (cutsitesByName[k]) {
      return false;
    }
    return (0, _lodash.includes)(k.toLowerCase(), queryString.toLowerCase());
  });
  if (!(0, _lodash.isEmpty)(enzymesByNameThatMatch)) {
    return /*#__PURE__*/_react["default"].createElement("div", null, "No Active Results.. These inactive enzymes match:", /*#__PURE__*/_react["default"].createElement("br", null), /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex"
      }
    }, (0, _lodash.flatMap)(enzymesByNameThatMatch, function (e, i) {
      if (i > 3) return [];
      return /*#__PURE__*/_react["default"].createElement(_AdditionalCutsiteInfoDialog.CutsiteTag, {
        onWrapperClick: closeDropDown,
        allRestrictionEnzymes: allRestrictionEnzymes,
        forceOpenCutsiteInfo: true,
        name: e.name,
        cutsitesByName: cutsitesByName,
        cutsitesByNameActive: cutsitesByName,
        key: i
      });
    })));
  }
  var hiddenEnzymesByNameThatMatch = (0, _lodash.pickBy)(_sequenceUtils.aliasedEnzymesByName, function (v, k) {
    if (cutsitesByName[k]) {
      return false;
    }
    return (0, _lodash.includes)(k.toLowerCase(), queryString.toLowerCase());
  });
  if (!(0, _lodash.isEmpty)(hiddenEnzymesByNameThatMatch)) {
    return /*#__PURE__*/_react["default"].createElement("div", null, onHiddenEnzymeAdd ? "These Hidden enzymes match, " + ((0, _lodash.map)(hiddenEnzymesByNameThatMatch).length > 1 ? "click one" : "click it") + " to add it to your enzyme library" : "These Hidden enzymes match, add them via the Manage Enzymes link", /*#__PURE__*/_react["default"].createElement("br", null), /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex"
      }
    }, (0, _lodash.flatMap)(hiddenEnzymesByNameThatMatch, function (e, i) {
      var _extends2;
      var res = (0, _sequenceUtils.cutSequenceByRestrictionEnzyme)(inputSequenceToTestAgainst, true, e);
      if (i > 3) return [];
      return /*#__PURE__*/_react["default"].createElement(_AdditionalCutsiteInfoDialog.CutsiteTag, {
        onWrapperClick: onHiddenEnzymeAdd ? function () {
          onHiddenEnzymeAdd(e, props);
        } : closeDropDown,
        allRestrictionEnzymes: allRestrictionEnzymes,
        forceOpenCutsiteInfo: !onHiddenEnzymeAdd,
        name: e.name,
        cutsitesByName: _extends({}, cutsitesByName, (_extends2 = {}, _extends2[e.name.toLowerCase()] = res, _extends2)),
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      });
    })));
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "noResultsTextPlusButton"
  }, "No results... Add enzymes to your list via the ", manageEnzymesLink, " link", " ");
});
function CutsiteFilter(props) {
  var onChangeHook = props.onChangeHook,
    _props$style = props.style,
    style = _props$style === void 0 ? {} : _props$style,
    filteredRestrictionEnzymes = props.filteredRestrictionEnzymes,
    isEnzymeFilterAndUpdate = props.isEnzymeFilterAndUpdate,
    _filteredRestrictionEnzymesUpdate = props.filteredRestrictionEnzymesUpdate,
    cutsitesByName = props.allCutsites.cutsitesByName,
    allCutsites = props.allCutsites,
    filteredCutsites = props.filteredCutsites,
    onHiddenEnzymeAdd = props.onHiddenEnzymeAdd,
    _props$closeDropDown = props.closeDropDown,
    closeDropDown = _props$closeDropDown === void 0 ? function () {} : _props$closeDropDown,
    manageEnzymesToLeft = props.manageEnzymesToLeft,
    enzymeManageOverride = props.enzymeManageOverride,
    enzymeGroupsOverride = props.enzymeGroupsOverride,
    editorName = props.editorName,
    additionalEnzymes = props.additionalEnzymes,
    isEnzymeFilterAnd = props.isEnzymeFilterAnd,
    sequenceData = props.sequenceData;
  // const [isEnzymeFilterAnd, setAnd] = tgUseLocalStorageState("isEnzymeFilterAnd", false);
  var showAndOr = filteredCutsites.cutsiteIntersectionCount > 0 && filteredRestrictionEnzymes.length > 1;
  var _useState = (0, _react.useState)(""),
    queryTracker = _useState[0],
    setQueryTracker = _useState[1];
  var renderOptions = function renderOptions(_ref, props) {
    var label = _ref.label,
      value = _ref.value,
      canBeHidden = _ref.canBeHidden;
    var filteredRestrictionEnzymes = props.filteredRestrictionEnzymes,
      filteredRestrictionEnzymesUpdate = props.filteredRestrictionEnzymesUpdate;
    return /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex",
        justifyContent: "space-between",
        width: "100%"
      }
    }, label, " ", canBeHidden && /*#__PURE__*/_react["default"].createElement(_core.Icon, {
      onClick: function onClick(e) {
        e.stopPropagation();
        filteredRestrictionEnzymesUpdate((0, _lodash.flatMap)(filteredRestrictionEnzymes, function (e) {
          if (e.value === value) return [];
          return e;
        }).concat({
          label: label,
          className: "veHiddenEnzyme",
          value: value,
          // hiddenEnzyme: true,
          isHidden: true,
          canBeHidden: canBeHidden
        }));
      },
      htmlTitle: "Hide this enzyme",
      className: "veHideEnzymeBtn",
      style: {
        paddingTop: 5
      },
      iconSize: 14,
      icon: "eye-off"
    }));
  };
  var filteredRestrictionEnzymesUpdate = function filteredRestrictionEnzymesUpdate(enzymes) {
    _filteredRestrictionEnzymesUpdate(enzymes);
    if (sequenceData === null || sequenceData === void 0 ? void 0 : sequenceData.id) {
      try {
        window.localStorage.setItem("tgInitialCutsiteFilter-" + sequenceData.id, JSON.stringify(enzymes.map(function (e) {
          return (0, _lodash.omit)(e, "canBeHidden", "nameArray", "label");
        })));
      } catch (err) {
        // eslint-disable-next-line no-console
        console.warn("err 872g4e setting enzymes for sequence:", err);
      }
    }
  };
  var userEnzymeGroups = enzymeGroupsOverride || window.getExistingEnzymeGroups();
  var options = [].concat((0, _lodash.map)(_specialCutsiteFilterOptions["default"], function (opt) {
    return opt;
  }), (0, _lodash.map)(userEnzymeGroups, function (nameArray, name) {
    return {
      label: (0, _AdditionalCutsiteInfoDialog.getUserGroupLabel)({
        nameArray: nameArray,
        name: name
      }),
      value: "__userCreatedGroup" + name,
      nameArray: nameArray
    };
  }), Object.keys(cutsitesByName).sort().map(function (key) {
    var numCuts = (cutsitesByName[key] || []).length;
    var label = (0, _AdditionalCutsiteInfoDialog.getCutsiteWithNumCuts)({
      numCuts: numCuts,
      name: numCuts ? cutsitesByName[key][0].name : key
    });
    return {
      canBeHidden: true,
      label: label,
      value: key
    };
  })).map(function (n) {
    return addClickableLabel(n, {
      closeDropDown: closeDropDown
    });
  });
  var value = filteredRestrictionEnzymes.map(function (filteredOpt) {
    var toRet;
    if (filteredOpt.cutsThisManyTimes || filteredOpt.isSpecialGroup) {
      toRet = filteredOpt;
    } else if (filteredOpt.value.includes("__userCreatedGroup")) {
      toRet = filteredOpt;
    } else {
      var _defaultEnzymesByName;
      var numCuts = (cutsitesByName[filteredOpt.value] || []).length;
      var label = (0, _AdditionalCutsiteInfoDialog.getCutsiteWithNumCuts)({
        numCuts: numCuts,
        name: numCuts ? cutsitesByName[filteredOpt.value][0].name : ((_defaultEnzymesByName = _sequenceUtils.defaultEnzymesByName[filteredOpt.value]) === null || _defaultEnzymesByName === void 0 ? void 0 : _defaultEnzymesByName.name) || filteredOpt.value
      });
      toRet = _extends({}, filteredOpt, {
        label: label
      });
    }
    return addClickableLabel(toRet, {
      closeDropDown: closeDropDown
    });
  });
  var numEnzymesInAnd = filteredCutsites.cutsiteIntersectionCount;
  var numEnzymesInOr = filteredCutsites.cutsiteTotalCount;
  var numGroups = filteredRestrictionEnzymes.length;
  var onManageClick = function onManageClick() {
    enzymeManageOverride ? enzymeManageOverride(props) : (0, _GlobalDialogUtils.showDialog)({
      dialogType: "EnzymesDialog"
      // inputSequenceToTestAgainst: sequenceData ? sequenceData.sequence : ""
    });

    closeDropDown();
  };
  var manageEnzymesLink = /*#__PURE__*/_react["default"].createElement("a", {
    onClick: onManageClick,
    style: {
      width: "fit-content",
      fontSize: 11
    }
  }, "\u7BA1\u7406\u5185\u5207\u9176");
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, manageEnzymesToLeft && /*#__PURE__*/_react["default"].createElement(_core.Button, {
    minimal: true,
    "data-tip": "Manage Enzymes",
    onClick: onManageClick,
    icon: "cog"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    style: _extends({
      display: "flex",
      flexDirection: "column",
      flexWrap: "wrap"
    }, style)
  }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.TgSelect, {
    additionalRightEl: showAndOr ? /*#__PURE__*/_react["default"].createElement(_core.Tooltip, {
      modifiers: _teselagenReactComponents.popoverOverflowModifiers,
      content: isEnzymeFilterAnd ? "AND -- Viewing " + numEnzymesInAnd + " enzymes that are shared by " + (numGroups === 2 ? "both groups" : "all " + numGroups + " groups") : "OR -- Viewing " + numEnzymesInOr + " enzymes that are in any of the " + numGroups + " groups"
    }, /*#__PURE__*/_react["default"].createElement(_core.Tag, {
      minimal: true,
      interactive: true,
      style: {
        display: "flex",
        marginTop: 5
      },
      onClick: function onClick(e) {
        e.stopPropagation();
        isEnzymeFilterAndUpdate(!isEnzymeFilterAnd);
      }
    }, /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        color: isEnzymeFilterAnd ? "#ce5bce" : "darkgray"
      }
    }, "AND"), "/", /*#__PURE__*/_react["default"].createElement("span", {
      style: {
        color: !isEnzymeFilterAnd ? "#ce5bce" : "darkgray"
      }
    }, "OR"))) : false,
    multi: true,
    allowCreate: true,
    wrapperStyle: {
      zIndex: 11
    },
    noResultsText: /*#__PURE__*/_react["default"].createElement(NoResults, {
      inputSequenceToTestAgainst: sequenceData.sequence,
      manageEnzymesLink: manageEnzymesLink,
      closeDropDown: closeDropDown,
      onHiddenEnzymeAdd: onHiddenEnzymeAdd,
      queryString: queryTracker,
      additionalEnzymes: additionalEnzymes,
      enzymeGroupsOverride: enzymeGroupsOverride,
      cutsitesByNameActive: filteredCutsites.cutsitesByName,
      cutsitesByName: allCutsites.cutsitesByName,
      editorName: editorName
    }),
    onInputChange: function onInputChange(queryTracker) {
      setQueryTracker(queryTracker);
    },
    placeholder: "\u8FC7\u6EE4\u9176\u5207\u4F4D\u70B9...",
    options: options,
    filteredRestrictionEnzymes: filteredRestrictionEnzymes,
    filteredRestrictionEnzymesUpdate: filteredRestrictionEnzymesUpdate,
    optionRenderer: renderOptions,
    isSimpleSearch: true,
    onChange: function onChange(filteredRestrictionEnzymes) {
      onChangeHook && onChangeHook(filteredRestrictionEnzymes);
      filteredRestrictionEnzymesUpdate((0, _lodash.map)(filteredRestrictionEnzymes, function (r) {
        return (0, _lodash.omit)(r, ["label"]);
      }));
      // setShowFilterEnzymes(showAndOr);
    },

    value: value
  }), !manageEnzymesToLeft && /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex",
      justifyContent: "space-between"
    }
  }, manageEnzymesLink)));
}
var _default = (0, _redux.compose)(_withEditorProps["default"], (0, _reactRedux.connect)())(CutsiteFilter);
exports["default"] = _default;
function addClickableLabel(toRet, _ref2) {
  var closeDropDown = _ref2.closeDropDown;
  return _extends({}, toRet, toRet.label ? {
    label: (0, _AdditionalCutsiteInfoDialog.addCutsiteGroupClickHandler)({
      closeDropDown: closeDropDown,
      cutsiteOrGroupKey: toRet.value,
      el: toRet.label
    })
  } : {});
}