"use strict";

exports.__esModule = true;
exports.getUserGroupLabel = exports.getCutsiteWithNumCuts = exports.addCutsiteGroupClickHandler = exports.CutsiteTag = exports.CompareEnzymeGroupsDialog = exports.AdditionalCutsiteInfoDialog = void 0;
var _recompose = require("recompose");
var _teselagenReactComponents = require("teselagen-react-components");
var _react = _interopRequireDefault(require("react"));
var _core = require("@blueprintjs/core");
var _withEditorProps = _interopRequireDefault(require("../withEditorProps"));
var _specialCutsiteFilterOptions = _interopRequireDefault(require("../constants/specialCutsiteFilterOptions"));
var _lodash = require("lodash");
var _SingleEnzymeCutsiteInfo = _interopRequireDefault(require("../helperComponents/PropertiesDialog/SingleEnzymeCutsiteInfo"));
var _GlobalDialogUtils = require("../GlobalDialogUtils");
var _sequenceUtils = require("@teselagen/sequence-utils");
var _withRestrictionEnzymes = require("./withRestrictionEnzymes");
var _editorUtils = require("../utils/editorUtils");
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); }
function getUserEnzymeGroups(p) {
  return p.enzymeGroupsOverride || window.getExistingEnzymeGroups();
}
function isGroup(_ref) {
  var cutsiteOrGroupKey = _ref.cutsiteOrGroupKey;
  var isUserCreatedGroup = cutsiteOrGroupKey.startsWith("__userCreatedGroup");
  var specialCutsiteFilterOption = _specialCutsiteFilterOptions["default"][cutsiteOrGroupKey];
  return isUserCreatedGroup || specialCutsiteFilterOption;
}
var AdditionalCutsiteInfoDialog = (0, _recompose.compose)(_withEditorProps["default"], _withRestrictionEnzymes.withRestrictionEnzymes, (0, _teselagenReactComponents.wrapDialog)({
  isDraggable: true,
  getDialogProps: function getDialogProps(props) {
    if (isGroup(props)) {
      return {
        title: /*#__PURE__*/_react["default"].createElement("div", {
          style: {
            display: "flex"
          }
        }, "Group - \xA0", getGroupElAndCutsites(props).title)
      };
    } else {
      var c = props.allCutsites.cutsitesByName;
      var name = props.cutsiteOrGroupKey.toLowerCase();
      if (!c[name]) {
        var e = _sequenceUtils.aliasedEnzymesByName[name];
        if (e) {
          var _extends2;
          var res = (0, _sequenceUtils.cutSequenceByRestrictionEnzyme)(props.sequenceData.sequence, true, e);
          c = _extends({}, c, (_extends2 = {}, _extends2[name] = res, _extends2));
        }
      }
      return {
        title: /*#__PURE__*/_react["default"].createElement("div", {
          style: {
            display: "flex"
          }
        }, "Enzyme - \xA0", /*#__PURE__*/_react["default"].createElement(CutsiteTag, {
          noClick: true,
          showActiveText: true,
          allRestrictionEnzymes: props.allRestrictionEnzymes,
          cutsitesByNameActive: props.filteredCutsites.cutsitesByName,
          cutsitesByName: c,
          name: props.cutsiteOrGroupKey
        }))
      };
    }
  }
}))(function (props) {
  var dispatch = props.dispatch,
    editorName = props.editorName,
    cutsiteOrGroupKey = props.cutsiteOrGroupKey,
    cutsitesByName = props.allCutsites.cutsitesByName,
    cutsitesByNameActive = props.filteredCutsites.cutsitesByName,
    selectedAnnotationId = props.selectedAnnotationId,
    allRestrictionEnzymes = props.allRestrictionEnzymes;
  var inner;
  var userEnzymeGroups = getUserEnzymeGroups(props);
  if (isGroup(props)) {
    //group case
    var ret = getGroupElAndCutsites(props);
    var enzymesThatCutInSeq = ret.enzymesThatCutInSeq;
    var enzymesThatDontCutInSeq = ret.enzymesThatDontCutInSeq;
    inner = /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.DropdownButton, {
      minimal: true,
      menu: /*#__PURE__*/_react["default"].createElement(_core.Menu, null, (0, _lodash.flatMap)([].concat((0, _lodash.map)(_specialCutsiteFilterOptions["default"]), (0, _lodash.map)(userEnzymeGroups, function (v, key) {
        return {
          label: key,
          value: "__userCreatedGroup" + key
        };
      })), function (_ref2, key, i) {
        var label = _ref2.label,
          value = _ref2.value;
        if (value === cutsiteOrGroupKey) return [];
        return /*#__PURE__*/_react["default"].createElement(_core.MenuItem, {
          onClick: function onClick() {
            (0, _GlobalDialogUtils.showDialog)({
              dialogType: "CompareEnzymeGroupsDialog",
              props: {
                dialogProps: {
                  title: "Comparing Groups",
                  width: 450
                },
                group1: cutsiteOrGroupKey,
                group2: value
              }
            });
          },
          key: i,
          text: "vs " + label
        });
      })),
      text: "Compare.."
    }), /*#__PURE__*/_react["default"].createElement("br", null), /*#__PURE__*/_react["default"].createElement("br", null)), /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex",
        justifyContent: "space-between"
      }
    }, !!enzymesThatCutInSeq.length && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex",
        flexDirection: "column",
        overflow: "auto"
        // maxHeight: 400
      }
    }, enzymesThatCutInSeq.map(function (e, i) {
      return /*#__PURE__*/_react["default"].createElement(CutsiteTag, _extends({
        allRestrictionEnzymes: props.allRestrictionEnzymes,
        cutsitesByName: props.allCutsites.cutsitesByName,
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      }, e));
    }))), enzymesThatDontCutInSeq && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex",
        flexDirection: "column",
        overflow: "auto"
      }
    }, enzymesThatDontCutInSeq.map(function (e, i) {
      return /*#__PURE__*/_react["default"].createElement(CutsiteTag, _extends({
        allRestrictionEnzymes: props.allRestrictionEnzymes,
        cutsitesByName: props.allCutsites.cutsitesByName,
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      }, e));
    })))));
  } else if (
  //single enzyme case
  cutsitesByName[cutsiteOrGroupKey.toLowerCase()] || allRestrictionEnzymes[cutsiteOrGroupKey.toLowerCase()] || _sequenceUtils.aliasedEnzymesByName[cutsiteOrGroupKey.toLowerCase()]) {
    var inTheseUserGroups = [];
    var cutsiteGroup = cutsitesByName[cutsiteOrGroupKey.toLowerCase()] || [];
    var enzyme = cutsiteGroup[0] ? cutsiteGroup[0].restrictionEnzyme : allRestrictionEnzymes[cutsiteOrGroupKey.toLowerCase()] || _sequenceUtils.aliasedEnzymesByName[cutsiteOrGroupKey.toLowerCase()];
    if (cutsiteGroup.length && cutsiteGroup.length <= 3) {
      var _getGroupElAndCutsite = getGroupElAndCutsites(_extends({}, props, {
          cutsiteOrGroupKey: (0, _lodash.find)(_specialCutsiteFilterOptions["default"], function (_ref3) {
            var cutsThisManyTimes = _ref3.cutsThisManyTimes;
            return cutsThisManyTimes === cutsiteGroup.length;
          }).value
        })),
        el = _getGroupElAndCutsite.el;
      inTheseUserGroups.push(el);
    }
    var enzymeName = enzyme.name;
    (0, _lodash.forEach)(userEnzymeGroups, function (nameArray, name) {
      var isInGroup;
      (0, _lodash.forEach)(nameArray, function (n) {
        if (n.toLowerCase() === enzymeName.toLowerCase()) {
          isInGroup = true;
        }
      });
      if (isInGroup) {
        var _cutsiteOrGroupKey = "__userCreatedGroup" + name;
        var _getGroupElAndCutsite2 = getGroupElAndCutsites(_extends({}, props, {
            cutsiteOrGroupKey: _cutsiteOrGroupKey
          })),
          _el = _getGroupElAndCutsite2.el;
        inTheseUserGroups.push(_el);
      }
    });
    inner = /*#__PURE__*/_react["default"].createElement("div", null, !!inTheseUserGroups.length && /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        marginBottom: 20
      }
    }, inTheseUserGroups), /*#__PURE__*/_react["default"].createElement(_SingleEnzymeCutsiteInfo["default"], {
      dispatch: dispatch,
      editorName: editorName,
      selectedAnnotationId: selectedAnnotationId,
      cutsiteGroup: cutsiteGroup,
      enzyme: enzyme,
      allRestrictionEnzymes: allRestrictionEnzymes,
      allCutsites: props.allCutsites,
      filteredCutsites: props.filteredCutsites
    }));
  } else {
    console.error("we shouldn't be here!:", cutsiteOrGroupKey);
    return null;
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: _core.Classes.DIALOG_BODY
  }, inner);
});
exports.AdditionalCutsiteInfoDialog = AdditionalCutsiteInfoDialog;
var CompareEnzymeGroupsDialog = (0, _recompose.compose)(_withEditorProps["default"], _withRestrictionEnzymes.withRestrictionEnzymes, (0, _teselagenReactComponents.wrapDialog)({
  isDraggable: true
}))(function (props) {
  var group1 = props.group1,
    group2 = props.group2,
    cutsitesByNameActive = props.filteredCutsites.cutsitesByName;
  var g1 = getGroupElAndCutsites(_extends({}, props, {
    cutsiteOrGroupKey: group1
  }));
  var g2 = getGroupElAndCutsites(_extends({}, props, {
    cutsiteOrGroupKey: group2
  }));
  var byNameLower = function byNameLower(n) {
    return n.name.toLowerCase();
  };
  var shared = (0, _lodash.intersectionBy)(g1.allEnzymesInGroup, g2.allEnzymesInGroup, byNameLower);
  var g1Only = (0, _lodash.differenceBy)(g1.allEnzymesInGroup, shared, byNameLower);
  var g2Only = (0, _lodash.differenceBy)(g2.allEnzymesInGroup, shared, byNameLower);
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex",
      justifyContent: "space-between"
    },
    className: _core.Classes.DIALOG_BODY
  }, /*#__PURE__*/_react["default"].createElement(Column, {
    dataTest: "tg-column-1",
    title: "In",
    header: g1.el,
    body: g1Only.map(function (e, i) {
      return /*#__PURE__*/_react["default"].createElement(CutsiteTag, _extends({
        allRestrictionEnzymes: props.allRestrictionEnzymes,
        cutsitesByName: props.allCutsites.cutsitesByName,
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      }, e));
    })
  }), /*#__PURE__*/_react["default"].createElement(Column, {
    dataTest: "tg-column-2",
    title: "In Both",
    header: /*#__PURE__*/_react["default"].createElement("div", null, g1.el, " ", g2.el),
    body: shared.map(function (e, i) {
      return /*#__PURE__*/_react["default"].createElement(CutsiteTag, _extends({
        allRestrictionEnzymes: props.allRestrictionEnzymes,
        cutsitesByName: props.allCutsites.cutsitesByName,
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      }, e));
    })
  }), /*#__PURE__*/_react["default"].createElement(Column, {
    dataTest: "tg-column-3",
    title: "In",
    header: g2.el,
    body: g2Only.map(function (e, i) {
      return /*#__PURE__*/_react["default"].createElement(CutsiteTag, _extends({
        allRestrictionEnzymes: props.allRestrictionEnzymes,
        cutsitesByName: props.allCutsites.cutsitesByName,
        cutsitesByNameActive: cutsitesByNameActive,
        key: i
      }, e));
    })
  }));
});
exports.CompareEnzymeGroupsDialog = CompareEnzymeGroupsDialog;
function isUserEnzymeGroup(group) {
  var isUserCreatedGroup = group.startsWith("__userCreatedGroup");
  return isUserCreatedGroup;
}
var getGroupElAndCutsites = function getGroupElAndCutsites(_ref4) {
  var enzymeGroupsOverride = _ref4.enzymeGroupsOverride,
    cutsiteOrGroupKey = _ref4.cutsiteOrGroupKey,
    filteredRestrictionEnzymes = _ref4.filteredRestrictionEnzymes,
    allCutsites = _ref4.allCutsites;
  var userEnzymeGroups = enzymeGroupsOverride || window.getExistingEnzymeGroups();
  var isGroupActive;
  var label;
  var enzymesThatDontCutInSeq = [];
  var enzymesThatCutInSeq = [];
  (0, _lodash.forEach)(filteredRestrictionEnzymes, function (g) {
    if (g.value === cutsiteOrGroupKey) {
      isGroupActive = true;
    }
  });
  if (cutsiteOrGroupKey === "type2s") {
    var nameArray = (0, _lodash.flatMap)(_sequenceUtils.defaultEnzymesByName, function (e) {
      return e.isType2S ? e.name : [];
    });
    label = "Type IIS Enzymes";
    (0, _lodash.sortBy)(nameArray).forEach(function (name) {
      var cutsites = allCutsites.cutsitesByName[name.toLowerCase()];
      if (!cutsites) {
        enzymesThatDontCutInSeq.push({
          name: name,
          sites: []
        });
      } else {
        enzymesThatCutInSeq.push({
          name: name,
          sites: cutsites
        });
      }
    });
  } else if (isUserEnzymeGroup(cutsiteOrGroupKey)) {
    var name = cutsiteOrGroupKey.replace("__userCreatedGroup", "");
    var _nameArray = userEnzymeGroups[name];
    label = getUserGroupLabel({
      name: name,
      nameArray: _nameArray
    });
    (0, _lodash.sortBy)(_nameArray).forEach(function (name) {
      var cutsites = allCutsites.cutsitesByName[name.toLowerCase()];
      if (!cutsites) {
        enzymesThatDontCutInSeq.push({
          name: name,
          sites: []
        });
      } else {
        enzymesThatCutInSeq.push({
          name: name,
          sites: cutsites
        });
      }
    });
  } else {
    //it's a single/double/etc
    var specialCutsiteFilterOption = _specialCutsiteFilterOptions["default"][cutsiteOrGroupKey];
    label = specialCutsiteFilterOption.label;
    enzymesThatCutInSeq = (0, _lodash.map)(allCutsites.cutsitesByName, function (cutsites) {
      return cutsites.length === specialCutsiteFilterOption.cutsThisManyTimes ? {
        name: cutsites[0].name,
        sites: cutsites
      } : null;
    }).filter(function (n) {
      return n !== null;
    });
  }
  var title = /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex"
    }
  }, label, " \xA0", isGroupActive ? "" : "(inactive)");
  var el = addCutsiteGroupClickHandler({
    cutsiteOrGroupKey: cutsiteOrGroupKey,
    el: /*#__PURE__*/_react["default"].createElement(_core.Tag, {
      minimal: true,
      intent: isGroupActive && "primary",
      style: {
        margin: 3
      }
    }, label),
    title: title
  });
  return {
    el: el,
    title: title,
    enzymesThatDontCutInSeq: enzymesThatDontCutInSeq,
    enzymesThatCutInSeq: enzymesThatCutInSeq,
    allEnzymesInGroup: [].concat(enzymesThatCutInSeq, enzymesThatDontCutInSeq)
    // cutsitesInGroup: [] //tnrtodo
  };
};

var CutsiteTag = function CutsiteTag(_ref5) {
  var allRestrictionEnzymes = _ref5.allRestrictionEnzymes,
    showActiveText = _ref5.showActiveText,
    cutsitesByNameActive = _ref5.cutsitesByNameActive,
    cutsitesByName = _ref5.cutsitesByName,
    name = _ref5.name,
    onWrapperClick = _ref5.onWrapperClick,
    doNotShowCuts = _ref5.doNotShowCuts,
    noClick = _ref5.noClick,
    forceOpenCutsiteInfo = _ref5.forceOpenCutsiteInfo;
  var isHidden = getIsEnzymeHidden({
    name: name,
    allRestrictionEnzymes: allRestrictionEnzymes
  });
  var numCuts = (cutsitesByName[name.toLowerCase()] || []).length;
  var aliases = (0, _editorUtils.getEnzymeAliases)(name);
  aliases.forEach(function (alias) {
    if (numCuts === 0) {
      numCuts = (cutsitesByName[alias.toLowerCase()] || []).length;
    }
  });
  var isActive = numCuts ? cutsitesByNameActive[name.toLowerCase()] ? "primary" : undefined : undefined;
  var el = /*#__PURE__*/_react["default"].createElement(_core.Tag, {
    onClick: onWrapperClick,
    intent: isActive,
    style: {
      margin: 3,
      opacity: isHidden ? 0.5 : 1
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex"
    }
  }, getCutsiteWithNumCuts({
    name: name,
    numCuts: numCuts,
    doNotShowCuts: doNotShowCuts
  }), showActiveText ? isHidden ? /*#__PURE__*/_react["default"].createElement("span", null, "\xA0 hidden") : isActive ? /*#__PURE__*/_react["default"].createElement("span", null, "\xA0 active") : /*#__PURE__*/_react["default"].createElement("span", null, "\xA0 inactive") : null));
  return addCutsiteGroupClickHandler({
    el: el,
    noClick: noClick,
    cutsiteOrGroupKey: name,
    forceOpenCutsiteInfo: forceOpenCutsiteInfo
  });
};
exports.CutsiteTag = CutsiteTag;
var getUserGroupLabel = function getUserGroupLabel(_ref6) {
  var name = _ref6.name,
    nameArray = _ref6.nameArray;
  return /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      display: "flex",
      alignItems: "center"
    },
    title: "User created enzyme group " + name + " -- " + nameArray.join(" ")
  }, /*#__PURE__*/_react["default"].createElement(_core.Icon, {
    size: 10,
    icon: "user"
  }), "\xA0", name);
};
exports.getUserGroupLabel = getUserGroupLabel;
var getCutsiteWithNumCuts = function getCutsiteWithNumCuts(_ref7) {
  var name = _ref7.name,
    numCuts = _ref7.numCuts,
    doNotShowCuts = _ref7.doNotShowCuts;
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between"
    }
  }, " ", /*#__PURE__*/_react["default"].createElement("div", null, name), " ", !doNotShowCuts && /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      fontSize: 12
    }
  }, "\xA0(", numCuts, " cut", numCuts === 1 ? "" : "s", ")"));
};
exports.getCutsiteWithNumCuts = getCutsiteWithNumCuts;
var addCutsiteGroupClickHandler = function addCutsiteGroupClickHandler(_ref8) {
  var _ref8$closeDropDown = _ref8.closeDropDown,
    closeDropDown = _ref8$closeDropDown === void 0 ? function () {} : _ref8$closeDropDown,
    cutsiteOrGroupKey = _ref8.cutsiteOrGroupKey,
    el = _ref8.el,
    noClick = _ref8.noClick,
    forceOpenCutsiteInfo = _ref8.forceOpenCutsiteInfo;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: noClick ? "tg-cutsite-label" : "tg-clickable-cutsite-label",
    style: noClick ? {} : {
      cursor: "pointer"
    },
    onClick: noClick ? undefined : function (e) {
      var isInMultiSelect = e.target.closest(".bp3-multi-select-popover");
      if (!forceOpenCutsiteInfo && isInMultiSelect) return true;
      closeDropDown();
      (0, _GlobalDialogUtils.showDialog)({
        dialogType: "AdditionalCutsiteInfoDialog",
        props: {
          cutsiteOrGroupKey: cutsiteOrGroupKey
        }
      });
    }
  }, el);
};
exports.addCutsiteGroupClickHandler = addCutsiteGroupClickHandler;
function Column(_ref9) {
  var dataTest = _ref9.dataTest,
    header = _ref9.header,
    body = _ref9.body,
    title = _ref9.title;
  return /*#__PURE__*/_react["default"].createElement("div", {
    "data-test": dataTest,
    style: {
      flexGrow: "1",
      flexBasis: "0"
    }
  }, title, ":", /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      height: 60,
      marginBottom: 20,
      borderBottom: "1px solid lightgrey"
    }
  }, header), body);
}
function getIsEnzymeHidden(_ref10) {
  var name = _ref10.name,
    allRestrictionEnzymes = _ref10.allRestrictionEnzymes;
  var isHidden = true;
  if (allRestrictionEnzymes[name.toLowerCase()]) {
    isHidden = false;
  }
  return isHidden;
}