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); }
/* eslint-disable jsx-a11y/anchor-is-valid */
import { connect } from "react-redux";
import { compose } from "redux";
import { Button, Icon, Tag, Tooltip } from "@blueprintjs/core";
import withEditorProps from "../withEditorProps";
import specialCutsiteFilterOptions from "../constants/specialCutsiteFilterOptions";
import React, { useState } from "react";
import "./style.css";
import { popoverOverflowModifiers, TgSelect } from "teselagen-react-components";
import { map, flatMap, includes, pickBy, isEmpty } from "lodash";
import { omit } from "lodash";
import { showDialog } from "../GlobalDialogUtils";
import { addCutsiteGroupClickHandler, CutsiteTag, getCutsiteWithNumCuts, getUserGroupLabel } from "./AdditionalCutsiteInfoDialog";
import { withRestrictionEnzymes } from "./withRestrictionEnzymes";
import { aliasedEnzymesByName, cutSequenceByRestrictionEnzyme, defaultEnzymesByName } from "@teselagen/sequence-utils";
var NoResults = 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 = pickBy(allRestrictionEnzymes, function (v, k) {
    if (cutsitesByName[k]) {
      return false;
    }
    return includes(k.toLowerCase(), queryString.toLowerCase());
  });
  if (!isEmpty(enzymesByNameThatMatch)) {
    return /*#__PURE__*/React.createElement("div", null, "No Active Results.. These inactive enzymes match:", /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("div", {
      style: {
        display: "flex"
      }
    }, flatMap(enzymesByNameThatMatch, function (e, i) {
      if (i > 3) return [];
      return /*#__PURE__*/React.createElement(CutsiteTag, {
        onWrapperClick: closeDropDown,
        allRestrictionEnzymes: allRestrictionEnzymes,
        forceOpenCutsiteInfo: true,
        name: e.name,
        cutsitesByName: cutsitesByName,
        cutsitesByNameActive: cutsitesByName,
        key: i
      });
    })));
  }
  var hiddenEnzymesByNameThatMatch = pickBy(aliasedEnzymesByName, function (v, k) {
    if (cutsitesByName[k]) {
      return false;
    }
    return includes(k.toLowerCase(), queryString.toLowerCase());
  });
  if (!isEmpty(hiddenEnzymesByNameThatMatch)) {
    return /*#__PURE__*/React.createElement("div", null, onHiddenEnzymeAdd ? "These Hidden enzymes match, " + (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.createElement("br", null), /*#__PURE__*/React.createElement("div", {
      style: {
        display: "flex"
      }
    }, flatMap(hiddenEnzymesByNameThatMatch, function (e, i) {
      var _extends2;
      var res = cutSequenceByRestrictionEnzyme(inputSequenceToTestAgainst, true, e);
      if (i > 3) return [];
      return /*#__PURE__*/React.createElement(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.createElement("div", {
    className: "noResultsTextPlusButton"
  }, "No results... Add enzymes to your list via the ", manageEnzymesLink, " link", " ");
});
export 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 = 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.createElement("div", {
      style: {
        display: "flex",
        justifyContent: "space-between",
        width: "100%"
      }
    }, label, " ", canBeHidden && /*#__PURE__*/React.createElement(Icon, {
      onClick: function onClick(e) {
        e.stopPropagation();
        filteredRestrictionEnzymesUpdate(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 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(map(specialCutsiteFilterOptions, function (opt) {
    return opt;
  }), map(userEnzymeGroups, function (nameArray, name) {
    return {
      label: getUserGroupLabel({
        nameArray: nameArray,
        name: name
      }),
      value: "__userCreatedGroup" + name,
      nameArray: nameArray
    };
  }), Object.keys(cutsitesByName).sort().map(function (key) {
    var numCuts = (cutsitesByName[key] || []).length;
    var label = 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 = getCutsiteWithNumCuts({
        numCuts: numCuts,
        name: numCuts ? cutsitesByName[filteredOpt.value][0].name : ((_defaultEnzymesByName = 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) : showDialog({
      dialogType: "EnzymesDialog"
      // inputSequenceToTestAgainst: sequenceData ? sequenceData.sequence : ""
    });

    closeDropDown();
  };
  var manageEnzymesLink = /*#__PURE__*/React.createElement("a", {
    onClick: onManageClick,
    style: {
      width: "fit-content",
      fontSize: 11
    }
  }, "\u7BA1\u7406\u5185\u5207\u9176");
  return /*#__PURE__*/React.createElement(React.Fragment, null, manageEnzymesToLeft && /*#__PURE__*/React.createElement(Button, {
    minimal: true,
    "data-tip": "Manage Enzymes",
    onClick: onManageClick,
    icon: "cog"
  }), /*#__PURE__*/React.createElement("div", {
    style: _extends({
      display: "flex",
      flexDirection: "column",
      flexWrap: "wrap"
    }, style)
  }, /*#__PURE__*/React.createElement(TgSelect, {
    additionalRightEl: showAndOr ? /*#__PURE__*/React.createElement(Tooltip, {
      modifiers: 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.createElement(Tag, {
      minimal: true,
      interactive: true,
      style: {
        display: "flex",
        marginTop: 5
      },
      onClick: function onClick(e) {
        e.stopPropagation();
        isEnzymeFilterAndUpdate(!isEnzymeFilterAnd);
      }
    }, /*#__PURE__*/React.createElement("span", {
      style: {
        color: isEnzymeFilterAnd ? "#ce5bce" : "darkgray"
      }
    }, "AND"), "/", /*#__PURE__*/React.createElement("span", {
      style: {
        color: !isEnzymeFilterAnd ? "#ce5bce" : "darkgray"
      }
    }, "OR"))) : false,
    multi: true,
    allowCreate: true,
    wrapperStyle: {
      zIndex: 11
    },
    noResultsText: /*#__PURE__*/React.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(map(filteredRestrictionEnzymes, function (r) {
        return omit(r, ["label"]);
      }));
      // setShowFilterEnzymes(showAndOr);
    },

    value: value
  }), !manageEnzymesToLeft && /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex",
      justifyContent: "space-between"
    }
  }, manageEnzymesLink)));
}
export default compose(withEditorProps, connect())(CutsiteFilter);
function addClickableLabel(toRet, _ref2) {
  var closeDropDown = _ref2.closeDropDown;
  return _extends({}, toRet, toRet.label ? {
    label: addCutsiteGroupClickHandler({
      closeDropDown: closeDropDown,
      cutsiteOrGroupKey: toRet.value,
      el: toRet.label
    })
  } : {});
}