"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _teselagenReactComponents = require("teselagen-react-components");
var _sequenceUtils = require("@teselagen/sequence-utils");
var _AddOrEditAnnotationDialog = _interopRequireDefault(require("../AddOrEditAnnotationDialog"));
var _rangeUtils = require("@teselagen/range-utils");
var _editorUtils = require("../../utils/editorUtils");
var _classnames = _interopRequireDefault(require("classnames"));
require("./style.css");
var _lodash = require("lodash");
var _EditCaretPosition = _interopRequireWildcard(require("./EditCaretPosition"));
var _core = require("@blueprintjs/core");
var _MeltingTemp = _interopRequireDefault(require("../../StatusBar/MeltingTemp"));
var _getStructuredBases2 = require("../../RowItem/StackedAnnotations/getStructuredBases");
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 _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 _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 CustomContentEditable = (0, _teselagenReactComponents.generateField)(function CustomContentEditable(_ref) {
  var input = _ref.input,
    disabled = _ref.disabled,
    sequenceData = _ref.sequenceData,
    sequenceLength = _ref.sequenceLength,
    start = _ref.start,
    end = _ref.end,
    primerBindsOn = _ref.primerBindsOn,
    bases = _ref.bases,
    forward = _ref.forward;
  var _useState = (0, _react.useState)(false),
    hasTempError = _useState[0],
    setTempError = _useState[1];
  var inputRef = (0, _react.useRef)(null);
  var _useState2 = (0, _react.useState)({
      start: 0,
      end: 0
    }),
    caretPosition = _useState2[0],
    setCaretPosition = _useState2[1];
  var emitChange = function emitChange(e) {
    var newVal = e.target.innerText;
    var savedCaretPosition = _EditCaretPosition["default"].saveSelection(e.currentTarget);
    setCaretPosition(savedCaretPosition);
    var acceptedChars = (0, _editorUtils.getAcceptedChars)(sequenceData);
    var newBases = "";
    newVal.split("").forEach(function (letter) {
      if (acceptedChars.includes(letter.toLowerCase())) {
        newBases += letter;
      }
    });
    if (newVal.length !== newBases.length) {
      setTempError(true);
      setTimeout(function () {
        setTempError(false);
      }, 200);
    }
    var restore = (0, _EditCaretPosition.selectionSaveCaretPosition)(inputRef.current);
    input.onChange(newBases || "");
    setTimeout(function () {
      restore();
    }, 0);
  };
  (0, _react.useEffect)(function () {
    _EditCaretPosition["default"].restoreSelection(inputRef.current, caretPosition);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bases]);
  var basesToUse = bases || "";
  var _getStructuredBases = (0, _getStructuredBases2.getStructuredBases)({
      annotationRange: {
        start: start - 1,
        end: end - 1
      },
      forward: forward,
      bases: basesToUse,
      start: start - 1,
      end: end - 1,
      fullSequence: sequenceData.sequence,
      primerBindsOn: primerBindsOn,
      sequenceLength: sequenceLength
    }),
    allBasesWithMetaData = _getStructuredBases.allBasesWithMetaData;
  var html = (0, _lodash.flatMap)(allBasesWithMetaData, function (_ref2) {
    var b = _ref2.b,
      isMatch = _ref2.isMatch,
      isAmbiguousMatch = _ref2.isAmbiguousMatch;
    if (b === "&") return [];
    return "<span class=\"" + (isMatch ? "" : isAmbiguousMatch ? "tg-ambiguous-match-seq" : "tg-no-match-seq") + "\">" + b + "</span>";
  });
  html = html.join("");
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: _extends({
      display: "flex"
    }, disabled ? {
      pointerEvents: "none"
    } : {})
  }, /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      verticalAlign: "top",
      marginTop: 9,
      marginRight: 3,
      fontSize: 12,
      color: "grey"
    }
  }, "5'"), /*#__PURE__*/_react["default"].createElement("span", {
    ref: inputRef,
    spellCheck: "false",
    contentEditable: !disabled,
    className: (0, _classnames["default"])("bp3-input tg-custom-sequence-editable", {
      hasTempError: hasTempError
    }),
    onInput: emitChange,
    dangerouslySetInnerHTML: {
      __html: html
    } // innerHTML of the editable div
  }), /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      alignSelf: "end",
      marginBottom: 9,
      marginLeft: 3,
      fontSize: 12,
      color: "grey"
    }
  }, "3'"));
});
var RenderBases = function RenderBases(props) {
  var sequenceData = props.sequenceData,
    readOnly = props.readOnly,
    start = props.start,
    end = props.end,
    linkedOligo = props.linkedOligo,
    getLinkedOligoLink = props.getLinkedOligoLink,
    useLinkedOligo = props.useLinkedOligo,
    sequenceLength = props.sequenceLength,
    primerBindsOn = props.primerBindsOn,
    bases = props.bases,
    forward = props.forward,
    defaultLinkedOligoMessage = props.defaultLinkedOligoMessage,
    change = props.change;
  var defaultValue;
  var seqLen = sequenceData.sequence.length;
  var validate = (0, _react.useMemo)(function () {
    return function (val /* vals, props */) {
      if (!val) return;
      if (val.length > seqLen) {
        return "Primer cannot be longer than sequence";
      }
      return;
    };
  }, [seqLen]);
  var normalizedSelection = (0, _rangeUtils.convertRangeTo0Based)({
    start: start,
    end: end
  });
  if (!bases) {
    var bps = (0, _rangeUtils.getSequenceWithinRange)(normalizedSelection, sequenceData.sequence);
    if (!forward) {
      bps = (0, _sequenceUtils.getReverseComplementSequenceString)(bps);
    }
    defaultValue = bps;
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      borderTop: "1px solid #A7B6C2",
      borderBottom: "1px solid #A7B6C2"
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between"
    }
  }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.CheckboxField, {
    name: "useLinkedOligo",
    label: "Linked Oligo?",
    tooltipInfo: "Check this box to link this primer to an oligo in your Oligo Library. If the primer bases match exactly the bases of an existing oligo, it will be linked to that existing oligo. If the bases don't match, a new oligo will be created in the library.",
    noMarginBottom: true,
    defaultValue: true,
    disabled: readOnly
  }), useLinkedOligo && /*#__PURE__*/_react["default"].createElement("div", {
    className: "tg-linked-oligo-holder",
    style: {
      marginTop: -5,
      fontStyle: "italic",
      fontSize: 11
    }
  }, getLinkedOligoLink && getLinkedOligoLink(props) || linkedOligo || (defaultLinkedOligoMessage !== undefined ? defaultLinkedOligoMessage : "Will Be Created On Save"))), useLinkedOligo && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(CustomContentEditable
  // inlineLabel
  , _extends({
    showErrorIfUntouched: true,
    tooltipError: true,
    primerBindsOn: primerBindsOn,
    validate: validate,
    sequenceLength: sequenceLength,
    disabled: readOnly
  }, props, defaultValue ? {
    defaultValue: defaultValue
  } : {}, {
    name: "bases",
    label: /*#__PURE__*/_react["default"].createElement("div", {
      className: "tg-bases-label"
    }, /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex"
      }
    }, "Bases", " ", /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        fontSize: 10
      }
    }, " ", "\xA0 (Length: ", bases ? bases.length : 0, ")")), /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        width: "fit-content"
      }
    }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.DropdownButton, {
      disabled: readOnly,
      intent: "primary",
      small: true,
      menu: /*#__PURE__*/_react["default"].createElement(_core.Menu, null, /*#__PURE__*/_react["default"].createElement(_core.MenuItem, {
        onClick: function onClick() {
          change("forward", true);
          change("bases", (0, _rangeUtils.getSequenceWithinRange)(normalizedSelection, sequenceData.sequence));
        },
        key: "forward",
        text: "Forward"
      }), /*#__PURE__*/_react["default"].createElement(_core.MenuItem, {
        onClick: function onClick() {
          change("forward", false);
          change("bases", (0, _sequenceUtils.getReverseComplementSequenceString)((0, _rangeUtils.getSequenceWithinRange)(normalizedSelection, sequenceData.sequence)));
        },
        key: "reverse",
        text: "Reverse"
      }))
    }, "Set From Selection")))
  })), /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.AdvancedOptions, {
    style: {
      marginBottom: 10
    }
  }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.RadioGroupField, {
    name: "primerBindsOn",
    inline: true,
    inlineLabel: true,
    disabled: readOnly,
    label: "Oligo Binds On",
    tooltipError: true,
    options: [{
      label: "5' End",
      value: "5prime"
    }, {
      label: "3' End",
      value: "3prime"
    }]
  })), /*#__PURE__*/_react["default"].createElement(_MeltingTemp["default"], {
    InnerWrapper: InnerWrapperMeltingTemp,
    sequence: bases
  })));
};
var _default = (0, _AddOrEditAnnotationDialog["default"])({
  formName: "AddOrEditPrimerDialog",
  getProps: function getProps(props) {
    return {
      upsertAnnotation: props.upsertPrimer,
      annotationTypePlural: "primers",
      RenderBases: RenderBases
    };
  }
});
exports["default"] = _default;
var InnerWrapperMeltingTemp = function InnerWrapperMeltingTemp(p) {
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "bp3-text-muted bp3-text-small",
    style: {
      marginBottom: 15,
      marginTop: -5,
      fontStyle: "italic"
    }
  }, p.children);
};
module.exports = exports.default;