"use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _reduxForm = require("redux-form");
var _teselagenReactComponents = require("teselagen-react-components");
var _redux = require("redux");
var _core = require("@blueprintjs/core");
var _rangeUtils = require("@teselagen/range-utils");
var _sequenceUtils = require("@teselagen/sequence-utils");
var _classnames = _interopRequireDefault(require("classnames"));
var _reactEasyState = require("@risingstack/react-easy-state");
var _withEditorProps = _interopRequireDefault(require("../../withEditorProps"));
var _recompose = require("recompose");
var _lodash = require("lodash");
require("./style.css");
var _tgFormValues = _interopRequireDefault(require("../../utils/tgFormValues"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var AddOrEditAnnotationDialog = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(AddOrEditAnnotationDialog, _React$Component);
  function AddOrEditAnnotationDialog() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _defineProperty(_assertThisInitialized(_this), "formatStart", function (val) {
      var _ref = _this.props.sequenceData || {},
        isProtein = _ref.isProtein;
      if (isProtein) {
        return (val + 2) / 3;
      }
      return val;
    });
    _defineProperty(_assertThisInitialized(_this), "formatEnd", function (val) {
      var _ref2 = _this.props.sequenceData || {},
        isProtein = _ref2.isProtein;
      if (isProtein) {
        return val / 3;
      }
      return val;
    });
    _defineProperty(_assertThisInitialized(_this), "parseStart", function (val) {
      var _ref3 = _this.props.sequenceData || {},
        isProtein = _ref3.isProtein;
      if (isProtein) {
        return val * 3 - 2;
      }
      return val;
    });
    _defineProperty(_assertThisInitialized(_this), "parseEnd", function (val) {
      var _ref4 = _this.props.sequenceData || {},
        isProtein = _ref4.isProtein;
      if (isProtein) {
        return val * 3;
      }
      return val;
    });
    _defineProperty(_assertThisInitialized(_this), "renderLocations", function (props) {
      var fields = props.fields;
      var _this$props = _this.props,
        _this$props$sequenceD = _this$props.sequenceData,
        sequenceData = _this$props$sequenceD === void 0 ? {
          sequence: ""
        } : _this$props$sequenceD,
        start = _this$props.start,
        end = _this$props.end;
      var sequenceLength = sequenceData.sequence.length;
      var locations = fields.getAll() || [];
      return /*#__PURE__*/_react["default"].createElement("div", null, locations.length > 1 && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_core.Label, null, "\u52A0\u5165\u7684Feature\u8DE8\u8D8A"), /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          marginLeft: 50
        }
      }, !locations.length && /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          marginBottom: 10
        }
      }, "\u6CA1\u6709\u8FDB\u5360\u3002\u70B9\u51FB\u201C\u6DFB\u52A0\u4F4D\u7F6E\u201D\u6DFB\u52A0\u5B50\u4F4D\u7F6E \u5BF9\u4E8E\u8FD9\u4E2Afeature.", " "), fields.map(function (member, index) {
        //the locations will have already been converted to 1 based ranges
        return /*#__PURE__*/_react["default"].createElement("div", {
          style: {},
          key: index
        }, /*#__PURE__*/_react["default"].createElement("div", {
          style: {
            display: "flex",
            marginBottom: 10
          }
        }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.NumericInputField, {
          disabled: _this.props.readOnly,
          containerStyle: {
            marginBottom: 0,
            marginRight: 10
          },
          inlineLabel: true,
          className: "no-inline-label-margins",
          tooltipError: true,
          min: 1,
          format: _this.formatStart,
          parse: _this.parseStart,
          max: sequenceLength || 1,
          name: member + ".start",
          label: "\u5F00\u59CB"
        }), /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.NumericInputField, {
          disabled: _this.props.readOnly,
          containerStyle: {
            marginBottom: 0,
            marginRight: 10
          },
          inlineLabel: true,
          className: "no-inline-label-margins",
          tooltipError: true,
          min: 1,
          format: _this.formatEnd,
          parse: _this.parseEnd,
          max: sequenceLength || 1,
          name: member + ".end",
          label: "\u7ED3\u675F"
        }), /*#__PURE__*/_react["default"].createElement(_core.Button, {
          disabled: _this.props.readOnly,
          onClick: function onClick() {
            if (locations.length === 2) {
              fields.remove(0);
              fields.remove(1);
            } else {
              fields.remove(index);
            }
          },
          minimal: true,
          icon: "trash"
        })));
      }))), /*#__PURE__*/_react["default"].createElement(_core.Button, {
        disabled: _this.props.readOnly,
        style: {
          marginBottom: 10,
          left: "50%"
        }
        // intent="primary"
        ,
        onClick: function onClick() {
          if (locations && locations.length) {
            fields.push({
              start: locations[locations.length - 1].end + 1,
              end: locations[locations.length - 1].end + (sequenceData.isProtein ? 3 : 2)
            });
          } else {
            var end1 = Math.max(start, end - 10);
            fields.push({
              start: start,
              end: end1
            });
            fields.push({
              start: end1 + 3,
              end: end1 + 10
            });
          }
        },
        icon: "add"
      }, "\u6DFB\u52A0\u5DF2\u52A0\u5165\u7684Feature\u8303\u56F4"));
    });
    return _this;
  }
  var _proto = AddOrEditAnnotationDialog.prototype;
  _proto.componentDidMount = function componentDidMount() {
    var initialNotes = this.props.initialValues && this.props.initialValues.notes || {};
    this.notes = (0, _reactEasyState.store)((0, _lodash.flatMap)(initialNotes, function (noteValues, noteType) {
      return (0, _lodash.map)(noteValues, function (value) {
        return {
          key: noteType,
          value: value
        };
      });
    }));
  };
  _proto.render = function render() {
    var _this2 = this;
    var _this$props2 = this.props,
      defaultLinkedOligoMessage = _this$props2.defaultLinkedOligoMessage,
      hideModal = _this$props2.hideModal,
      _this$props2$sequence = _this$props2.sequenceData,
      sequenceData = _this$props2$sequence === void 0 ? {
        sequence: ""
      } : _this$props2$sequence,
      handleSubmit = _this$props2.handleSubmit,
      beforeAnnotationCreate = _this$props2.beforeAnnotationCreate,
      renderTypes = _this$props2.renderTypes,
      renderTags = _this$props2.renderTags,
      RenderBases = _this$props2.RenderBases,
      allowMultipleFeatureDirections = _this$props2.allowMultipleFeatureDirections,
      getLinkedOligoLink = _this$props2.getLinkedOligoLink,
      allowPrimerBasesToBeEdited = _this$props2.allowPrimerBasesToBeEdited,
      bases = _this$props2.bases,
      initialValues = _this$props2.initialValues,
      forward = _this$props2.forward,
      primerBindsOn = _this$props2.primerBindsOn,
      useLinkedOligo = _this$props2.useLinkedOligo,
      submitting = _this$props2.submitting,
      change = _this$props2.change,
      annotationTypePlural = _this$props2.annotationTypePlural,
      annotationVisibilityShow = _this$props2.annotationVisibilityShow,
      renderLocations = _this$props2.renderLocations,
      locations = _this$props2.locations,
      overlapsSelf = _this$props2.overlapsSelf,
      start = _this$props2.start,
      end = _this$props2.end,
      getAdditionalEditAnnotationComps = _this$props2.getAdditionalEditAnnotationComps,
      advancedOptions = _this$props2.advancedOptions,
      advancedDefaultOpen = _this$props2.advancedDefaultOpen,
      upsertAnnotation = _this$props2.upsertAnnotation,
      original_selectionLayerUpdate = _this$props2.original_selectionLayerUpdate;
    var isProtein = sequenceData.isProtein;
    var sequenceLength = sequenceData.sequence.length;
    var annotationLength = (0, _rangeUtils.getRangeLength)(locations && locations.length ? {
      start: locations[0].start,
      end: locations[locations.length - 1].end
    } : {
      start: start,
      end: end
    }, sequenceLength);
    return /*#__PURE__*/_react["default"].createElement("form", {
      onSubmit: handleSubmit( /*#__PURE__*/function () {
        var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(data) {
          var updatedData, forward, hasJoinedLocations, newAnnotation, shouldContinue;
          return _regeneratorRuntime().wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  forward = data.forward !== undefined ? data.forward : data.arrowheadType !== "BOTTOM"; // if (data.arrowheadType === "BOTH") {
                  //   data.arrowheadType = "BOTH";
                  // }
                  // if (data.arrowheadType === "NONE") {
                  //   data.arrowheadType = "NONE";
                  // }
                  // delete data.arrowheadType;
                  if (annotationTypePlural === "features" && allowMultipleFeatureDirections) {
                    updatedData = _extends({}, data, {
                      strand: data.arrowheadType === "BOTTOM" ? -1 : 1
                    });
                    delete updatedData.forward;
                  } else {
                    if (forward === true && data.strand !== 1) {
                      updatedData = _extends({}, data, {
                        strand: 1
                      });
                    } else if (forward === false && data.strand !== -1) {
                      updatedData = _extends({}, data, {
                        strand: -1
                      });
                    } else {
                      updatedData = data;
                    }
                  }
                  if (!data.useLinkedOligo) {
                    delete updatedData.bases;
                  }
                  updatedData.notes = {};
                  _this2.notes.forEach(function (_ref6) {
                    var key = _ref6.key,
                      value = _ref6.value;
                    if (!updatedData.notes[key]) updatedData.notes[key] = [];
                    updatedData.notes[key].push(value || "");
                  });
                  if (annotationTypePlural === "features") {
                    updatedData.color = _sequenceUtils.getFeatureToColorMap[updatedData.type];
                  }
                  hasJoinedLocations = updatedData.locations && updatedData.locations.length > 1;
                  newAnnotation = (0, _sequenceUtils.tidyUpAnnotation)((0, _rangeUtils.convertRangeTo0Based)(_extends({
                    overlapsSelf: data.overlapsSelf
                  }, updatedData, annotationTypePlural === "primers" //if we're making a primer it should automatically have a type of primer
                  ? {
                    type: "primer_bind"
                  } : {}, {
                    locations: undefined
                  }, hasJoinedLocations && {
                    //only add locations if there are locations
                    start: updatedData.locations[0].start,
                    //override the start and end to use the start and end of the joined locations
                    end: updatedData.locations[updatedData.locations.length - 1].end,
                    locations: updatedData.locations.map(_rangeUtils.convertRangeTo0Based)
                  })), {
                    sequenceData: sequenceData,
                    annotationType: annotationTypePlural
                  });
                  if (!beforeAnnotationCreate) {
                    _context.next = 14;
                    break;
                  }
                  _context.next = 11;
                  return beforeAnnotationCreate({
                    annotationTypePlural: annotationTypePlural,
                    annotation: newAnnotation,
                    props: _this2.props,
                    isEdit: !!_this2.props.initialValues.id
                  });
                case 11:
                  shouldContinue = _context.sent;
                  if (!(shouldContinue === false)) {
                    _context.next = 14;
                    break;
                  }
                  return _context.abrupt("return");
                case 14:
                  //update the selection layer so we don't jump away from where we're editing
                  //the original_ is there to differentiate it from the one we override to control the selection layer while in the dialog
                  original_selectionLayerUpdate && original_selectionLayerUpdate({
                    overlapsSelf: data.overlapsSelf,
                    start: newAnnotation.start,
                    end: newAnnotation.end
                  });
                  upsertAnnotation(newAnnotation);
                  annotationVisibilityShow(annotationTypePlural);
                  hideModal();
                case 18:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
        return function (_x) {
          return _ref5.apply(this, arguments);
        };
      }()),
      className: (0, _classnames["default"])(_core.Classes.DIALOG_BODY, "tg-min-width-dialog", "tg-upsert-annotation")
    }, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.InputField, _extends({
      disabled: this.props.readOnly,
      inlineLabel: true,
      tooltipError: true,
      autoFocus: true,
      placeholder: "\u65E0\u6807\u9898\u7684\u6CE8\u91CA"
    }, window.__getDefaultValGenerator && window.__getDefaultValGenerator({
      code: annotationTypePlural + "_name",
      customParams: {
        isProtein: isProtein,
        sequenceName: sequenceData.name,
        start: start,
        end: end
      }
    }), {
      validate: required,
      name: "name",
      label: "\u540D\u79F0"
    })), !isProtein && (annotationTypePlural === "features" && allowMultipleFeatureDirections ? /*#__PURE__*/_react["default"].createElement(StrandField, {
      name: "arrowheadType",
      label: "Strand",
      disabled: this.props.readOnly,
      inlineLabel: true,
      inline: true,
      tooltipError: true
    }) : /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.RadioGroupField, {
      disabled: this.props.readOnly,
      inlineLabel: true,
      inline: true,
      tooltipError: true,
      options: [{
        label: "正链",
        value: "true"
      }, {
        label: "负链",
        value: "false"
      }],
      normalize: function normalize(value) {
        return value === "true" || false;
      },
      format: function format(value) {
        return value ? "true" : "false";
      },
      name: "forward",
      label: "\u6B63\u8D1F\u94FE"
    })), renderTypes || null, renderTags || null, !renderLocations || !locations || locations.length < 2 ? /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        marginBottom: 10,
        fontSize: 12,
        fontStyle: "italic"
      }
    }, "\u53EF\u4F7F\u7528\u9F20\u6807\u6539\u53D8\u9009\u533A", " "), /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.NumericInputField, {
      inlineLabel: true,
      disabled: this.props.readOnly,
      format: this.formatStart,
      parse: this.parseStart,
      tooltipError: true,
      defaultValue: 1,
      min: 1,
      max: sequenceLength || 1,
      name: "start",
      label: "" + (annotationTypePlural === "primers" ? "开始位点" : "开始")
    }), /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.NumericInputField, {
      disabled: this.props.readOnly,
      format: this.formatEnd,
      parse: this.parseEnd,
      inlineLabel: true,
      tooltipError: true,
      defaultValue: sequenceData.isProtein ? 3 : 1,
      min: 1,
      max: sequenceLength || 1,
      name: "end",
      label: "" + (annotationTypePlural === "primers" ? "结束位点" : "结束")
    })) : null, renderLocations ? /*#__PURE__*/_react["default"].createElement(_reduxForm.FieldArray, {
      component: this.renderLocations,
      name: "locations"
    }) : null, /*#__PURE__*/_react["default"].createElement("div", {
      className: "bp3-text-muted bp3-text-small",
      style: {
        marginBottom: 15,
        marginTop: -5,
        fontStyle: "italic"
      }
    }, (annotationTypePlural === "primers" ? "结合位点" : "") + "\u957F\u5EA6: ", overlapsSelf ? sequenceLength + annotationLength : annotationLength), allowPrimerBasesToBeEdited && RenderBases ? /*#__PURE__*/_react["default"].createElement(RenderBases, {
      // ...this.props,
      bases: bases,
      defaultLinkedOligoMessage: defaultLinkedOligoMessage,
      getLinkedOligoLink: getLinkedOligoLink,
      readOnly: this.props.readOnly,
      sequenceData: sequenceData,
      start: start,
      end: end,
      initialValues: initialValues,
      sequenceLength: sequenceLength,
      primerBindsOn: primerBindsOn,
      forward: forward,
      linkedOligo: initialValues.linkedOligo,
      useLinkedOligo: useLinkedOligo,
      change: change
    }) : null, getAdditionalEditAnnotationComps && getAdditionalEditAnnotationComps(this.props), /*#__PURE__*/_react["default"].createElement(Notes, {
      readOnly: this.props.readOnly,
      notes: this.notes
    }), /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.AdvancedOptions, {
      isOpenByDefault: advancedDefaultOpen
    }, advancedOptions), /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        display: "flex",
        justifyContent: "flex-end"
      },
      className: "width100"
    }, /*#__PURE__*/_react["default"].createElement(_core.Button, {
      style: {
        marginRight: 15
      },
      onMouseDown: function onMouseDown(e) {
        //use onMouseDown to prevent issues with redux form errors popping in and stopping the dialog from closing
        e.preventDefault();
        e.stopPropagation();
        hideModal();
      }
    }, "\u53D6\u6D88"), /*#__PURE__*/_react["default"].createElement(_core.Button, {
      type: "submit",
      loading: submitting,
      disabled: this.props.readOnly,
      intent: _core.Intent.PRIMARY
    }, "\u4FDD\u5B58")));
  };
  return AddOrEditAnnotationDialog;
}(_react["default"].Component);
function required(val) {
  if (!val) return "必填";
}
var _default = function _default(_ref7) {
  var formName = _ref7.formName,
    getProps = _ref7.getProps,
    dialogProps = _ref7.dialogProps;
  return (0, _redux.compose)((0, _teselagenReactComponents.wrapDialog)(_extends({
    isDraggable: true,
    width: 400
  }, dialogProps)), _withEditorProps["default"], (0, _recompose.withProps)(getProps), (0, _reduxForm.reduxForm)({
    form: formName,
    // "AddOrEditAnnotationDialog",
    validate: function validate(values, _ref8) {
      var sequenceLength = _ref8.sequenceLength,
        sequenceData = _ref8.sequenceData;
      var errors = {};
      var _ref9 = sequenceData || {},
        circular = _ref9.circular;
      if (!circular && values.start > values.end) {
        errors.start = "Start must be less than End for a linear sequence";
        errors.end = "Start must be less than End for a linear sequence";
      }
      if (!(0, _rangeUtils.isRangeWithinRange)((0, _rangeUtils.convertRangeTo0Based)(values, sequenceLength), {
        start: 0,
        end: sequenceLength - 1
      }, sequenceLength)) {
        errors.start = "Range must fit within sequence";
        errors.end = "Range must fit within sequence";
      }
      if (values.locations && values.locations.length > 1) {
        var entireLocationSpan = {
          start: values.locations[0].start,
          end: values.locations[values.locations.length - 1].end
        };
        if (entireLocationSpan.start > entireLocationSpan.end && !circular) {
          errors.locations = errors.locations || {};
          errors.locations[0] = {
            start: "In a non-circular sequence, joined spans must be in ascending order"
          };
          errors.locations[values.locations.length - 1] = {
            end: "In a non-circular sequence, joined spans must be in ascending order"
          };
        }
        values.locations.forEach(function (loc, index) {
          // if (!isRangeWithinRange(loc, values, sequenceLength)) {
          //   errors.locations = errors.locations || {};
          //   errors.locations[index] = {
          //     start: "Range must fit within feature",
          //     end: "Range must fit within feature"
          //   };
          // }
          if (index !== 0 && index !== values.locations.length - 1) {
            //it is a middle location so it should fit within the parent location
            if (!(0, _rangeUtils.isRangeWithinRange)(loc, entireLocationSpan, sequenceLength)) {
              errors.locations = errors.locations || {};
              errors.locations[index] = {
                start: "Joined spans must be in ascending order",
                end: "Joined spans must be in ascending order"
              };
            }
          }
          values.locations.forEach(function (loc2, index2) {
            if (loc2 === loc) return;
            if ((0, _rangeUtils.checkIfPotentiallyCircularRangesOverlap)(loc, loc2)) {
              errors.locations = errors.locations || {};
              errors.locations[index] = {
                start: "Joined spans must not overlap",
                end: "Joined spans must not overlap"
              };
              errors.locations[index2] = {
                start: "Joined spans must not overlap",
                end: "Joined spans must not overlap"
              };
            }
          });
        });
      }
      return errors;
    }
  }), (0, _tgFormValues["default"])("start", "end", "overlapsSelf", "locations", "bases", "useLinkedOligo", "forward", "primerBindsOn"))(AddOrEditAnnotationDialog);
};
exports["default"] = _default;
var Notes = (0, _reactEasyState.view)(function (_ref10) {
  var readOnly = _ref10.readOnly,
    notes = _ref10.notes;
  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_core.FormGroup, {
    style: {
      marginBottom: 0
    },
    inline: true,
    label: "\u5907\u6CE8",
    labelInfo: "(\u5B57\u6BB5 -- \u503C)"
  }), (0, _lodash.map)(notes, function (note, i) {
    var _ref11 = note || {},
      value = _ref11.value,
      key = _ref11.key;
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: i,
      "data-test": "note-" + i,
      style: {
        display: "flex",
        padding: "4px 2px"
      }
    }, /*#__PURE__*/_react["default"].createElement(_core.EditableText, {
      onConfirm: function onConfirm(string) {
        if (string === "") {
          if (!note.value) {
            notes.splice(i, 1);
          } else {
            note.key = "note";
          }
        }
      },
      disabled: readOnly,
      placeholder: "Add key here",
      maxLines: 5,
      multiline: true,
      className: "addAnnNoteKey"
      // style={{marginRight: 20}}
      ,
      onChange: function onChange(string) {
        note.key = string.replace(" ", "_").replace(/\n/g, "");
      },
      value: key
    }), /*#__PURE__*/_react["default"].createElement(_core.EditableText, {
      disabled: readOnly,
      maxLines: 10,
      className: "addAnnNoteValue",
      multiline: true
      // style={{
      //   paddingTop: 6,
      //   height: 30,
      //   minHeight: 30,
      //   minWidth: 200,
      //   maxWidth: 200,
      // }}
      ,
      onChange: function onChange(string) {
        note.value = string.replace(/\n/g, "");
      },
      value: value
    }), " ", "\xA0", /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_core.Button, {
      disabled: readOnly,
      style: {
        padding: 2
      },
      onClick: function onClick() {
        notes.splice(i, 1);
      },
      minimal: true,
      icon: "trash"
    })));
  }), /*#__PURE__*/_react["default"].createElement(_core.Button, {
    disabled: readOnly,
    onClick: function onClick() {
      notes.push({
        key: "note",
        value: ""
      });
    },
    minimal: true,
    icon: "plus"
  }, " ", "\u6DFB\u52A0\u5907\u6CE8"));
});
var StrandField = (0, _teselagenReactComponents.generateField)(function (_ref12) {
  var input = _ref12.input;
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_core.Button, {
    title: "Bottom",
    className: "tg-arrowheadType-BOTTOM",
    active: input.value === "BOTTOM",
    minimal: true,
    style: {
      marginRight: 20
    },
    onClick: function onClick() {
      return input.onChange("BOTTOM");
    },
    icon: _teselagenReactComponents.reverseFeatureIcon
  }), /*#__PURE__*/_react["default"].createElement(_core.Button, {
    title: "No Direction",
    className: "tg-arrowheadType-NONE",
    active: input.value === "NONE",
    minimal: true,
    style: {
      marginRight: 20
    },
    onClick: function onClick() {
      return input.onChange("NONE");
    },
    icon: _teselagenReactComponents.bluntFeatureIcon
  }), /*#__PURE__*/_react["default"].createElement(_core.Button, {
    title: "Top",
    className: "tg-arrowheadType-TOP",
    onClick: function onClick() {
      return input.onChange("TOP");
    },
    minimal: true,
    active: input.value === "TOP",
    icon: _teselagenReactComponents.featureIcon
  }));
});
module.exports = exports.default;