"use strict";

exports.__esModule = true;
exports["default"] = void 0;
exports.getVisFilter = getVisFilter;
var _react = _interopRequireDefault(require("react"));
var _teselagenReactComponents = require("teselagen-react-components");
var _lodash = require("lodash");
var _core = require("@blueprintjs/core");
var _rangeUtils = require("@teselagen/range-utils");
var _withEditorProps = require("../../withEditorProps");
var _recompose = require("recompose");
var _commands = _interopRequireDefault(require("../../commands"));
var _utils = require("./utils");
var _GlobalDialogUtils = require("../../GlobalDialogUtils");
var _typeField = require("./typeField");
var _sequenceUtils = require("@teselagen/sequence-utils");
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 _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 genericAnnotationProperties = function genericAnnotationProperties(_ref) {
  var annotationType = _ref.annotationType,
    noType = _ref.noType,
    visSubmenu = _ref.visSubmenu,
    withTags = _ref.withTags,
    withBases = _ref.withBases,
    additionalFooterEls = _ref.additionalFooterEls;
  var annotationTypeUpper = (0, _lodash.upperFirst)(annotationType);
  var AnnotationProperties = /*#__PURE__*/function (_React$Component) {
    _inheritsLoose(AnnotationProperties, _React$Component);
    function AnnotationProperties(props) {
      var _this;
      _this = _React$Component.call(this, props) || this;
      _defineProperty(_assertThisInitialized(_this), "onRowSelect", function (_ref2) {
        var record = _ref2[0];
        if (!record) return;
        var _this$props = _this.props,
          dispatch = _this$props.dispatch,
          editorName = _this$props.editorName;
        dispatch({
          type: "SELECTION_LAYER_UPDATE",
          payload: record,
          meta: {
            editorName: editorName
          }
        });
      });
      _this.commands = (0, _commands["default"])(_assertThisInitialized(_this));
      _this.schema = {
        fields: [{
          path: "name",
          type: "string",
          displayName: "名称",
          render: function render(name, ann, row, props) {
            var checked = !props.annotationVisibility[annotationType + "IndividualToHide"][ann.id];
            return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_core.Icon, {
              "data-tip": "Hide/Show",
              onClick: function onClick(e) {
                e.stopPropagation();
                var upperType = (0, _lodash.startCase)(annotationType);
                if (checked) {
                  props["hide" + upperType + "Individual"]([ann.id]);
                } else {
                  props["show" + upperType + "Individual"]([ann.id]);
                }
              },
              style: {
                cursor: "pointer",
                marginRight: 4,
                marginTop: 3,
                color: "darkgray"
              },
              icon: "eye-" + (checked ? "open" : "off")
            }), name);
          }
        }].concat(!withBases ? [] : [{
          path: "bases",
          displayName: "基准",
          type: "string",
          render: function render(bases, primer, row, props) {
            var bps = bases;
            if (!bases) {
              bps = (0, _rangeUtils.getSequenceWithinRange)(primer, props.sequence);
              if (!primer.forward) {
                bps = (0, _sequenceUtils.getReverseComplementSequenceString)(bps);
              }
            }
            return bps;
          }
        }], noType ? [] : [_typeField.typeField, {
          path: "color",
          type: "string",
          displayName: "颜色",
          width: 50,
          render: function render(color) {
            return /*#__PURE__*/_react["default"].createElement("div", {
              style: {
                height: 20,
                width: 20,
                background: color
              }
            })
            // <ColorPickerPopover>
            //   <div style={{ height: 20, width: 20, background: color }} />
            // </ColorPickerPopover>
            ;
          }
        }], [_utils.sizeSchema], withTags && _this.props.allPartTags ? [{
          path: "tags",
          type: "string",
          getValueToFilterOn: function getValueToFilterOn(o, _ref3) {
            var keyedPartTags = _ref3.keyedPartTags;
            var toRet = (o.tags || []).map(function (tagId) {
              var tag = keyedPartTags[tagId];
              if (!tag) return "";
              return tag.label;
            }).join(" ");
            return toRet;
          },
          render: function render(tags, b, c, _ref4) {
            var _ref4$keyedPartTags = _ref4.keyedPartTags,
              keyedPartTags = _ref4$keyedPartTags === void 0 ? {} : _ref4$keyedPartTags;
            return /*#__PURE__*/_react["default"].createElement("div", {
              style: {
                display: "flex"
              }
            }, (tags || []).map(function (tagId, i) {
              var tag = keyedPartTags[tagId];
              if (!tag) return null;
              return /*#__PURE__*/_react["default"].createElement(_core.Tag, _extends({
                key: i
              }, (0, _teselagenReactComponents.getTagProps)(tag)));
            }));
          }
        }] : [], [{
          path: "strand",
          type: "number",
          displayName: "位于正/负链"
        }])
      };
      return _this;
    }
    var _proto = AnnotationProperties.prototype;
    _proto.render = function render() {
      var _this$props2 = this.props,
        readOnly = _this$props2.readOnly,
        _this$props2$annotati = _this$props2.annotations,
        annotations = _this$props2$annotati === void 0 ? {} : _this$props2$annotati,
        annotationVisibility = _this$props2.annotationVisibility,
        sequenceLength = _this$props2.sequenceLength,
        selectionLayer = _this$props2.selectionLayer,
        sequence = _this$props2.sequence,
        isProtein = _this$props2.isProtein,
        allPartTags = _this$props2.allPartTags,
        _annotationPropertiesSelectedEntities = _this$props2.annotationPropertiesSelectedEntities,
        selectedAnnotationId = _this$props2.selectedAnnotationId;
      var annotationPropertiesSelectedEntities = _annotationPropertiesSelectedEntities.filter(function (a) {
        return annotations[a.id];
      });
      var deleteAnnotation = this.props["delete" + annotationTypeUpper];
      var annotationsToUse = (0, _lodash.map)(annotations, function (annotation) {
        return _extends({}, annotation, annotation.strand === undefined && {
          strand: annotation.forward ? 1 : -1
        }, {
          size: (0, _rangeUtils.getRangeLength)(annotation, sequenceLength)
        });
      });
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.DataTable, {
        topLeftItems: getVisFilter((0, _teselagenReactComponents.createCommandMenu)((0, _lodash.isFunction)(visSubmenu) ? visSubmenu(this.props) : visSubmenu, this.commands, {
          useTicks: true
        })),
        annotationPropertiesSelectedEntities: annotationPropertiesSelectedEntities,
        leftOfSearchBarItems: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, !readOnly && /*#__PURE__*/_react["default"].createElement(_core.ButtonGroup, {
          style: {
            marginTop: 3,
            marginRight: 4
          }
        }, /*#__PURE__*/_react["default"].createElement(_core.Tooltip, {
          position: "top",
          modifiers: _teselagenReactComponents.popoverOverflowModifiers,
          content: "\u65B0\u5EFA"
        }, /*#__PURE__*/_react["default"].createElement(_core.AnchorButton, {
          disabled: !sequenceLength,
          icon: "plus",
          className: "tgNewAnnBtn",
          onClick: function onClick() {
            (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
              type: annotationType,
              annotation: (0, _lodash.pick)(selectionLayer, "start", "end", "forward")
            });
          }
        })), /*#__PURE__*/_react["default"].createElement(_core.Tooltip, {
          position: "top",
          modifiers: _teselagenReactComponents.popoverOverflowModifiers,
          content: "\u7F16\u8F91"
        }, /*#__PURE__*/_react["default"].createElement(_core.AnchorButton, {
          onClick: function onClick() {
            (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
              type: annotationType,
              annotation: annotationPropertiesSelectedEntities[0]
            });
          },
          disabled: annotationPropertiesSelectedEntities.length !== 1,
          icon: "edit"
        })), ["feature"].includes(annotationType) && /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.CmdButton, {
          text: "",
          icon: "cog",
          "data-tip": "Configure Feature Types",
          cmd: this.commands.onConfigureFeatureTypesClick
        }), ["part", "primer", "feature"].includes(annotationType) && /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.CmdButton, {
          text: "",
          icon: _teselagenReactComponents.removeDuplicatesIcon,
          "data-tip": "\u79FB\u9664\u91CD\u590D\u9879",
          cmd: this.commands["showRemoveDuplicatesDialog" + (annotationTypeUpper + "s")]
        }), additionalFooterEls && additionalFooterEls(this.props), /*#__PURE__*/_react["default"].createElement(_core.Tooltip, {
          position: "top",
          modifiers: _teselagenReactComponents.popoverOverflowModifiers,
          content: "\u5220\u9664"
        }, /*#__PURE__*/_react["default"].createElement(_core.AnchorButton, {
          onClick: function onClick() {
            deleteAnnotation(annotationPropertiesSelectedEntities);
          },
          className: "tgDeleteAnnsBtn",
          intent: "danger",
          disabled: !annotationPropertiesSelectedEntities.length,
          icon: "trash"
        })))),
        onDoubleClick: function onDoubleClick(annotation) {
          (0, _GlobalDialogUtils.showAddOrEditAnnotationDialog)({
            type: annotationType,
            annotation: annotation
          });
        },
        withCheckboxes: true,
        showFeatureIndividual: this.props.showFeatureIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        hideFeatureIndividual: this.props.hideFeatureIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        showPartIndividual: this.props.showPartIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        hidePartIndividual: this.props.hidePartIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        showPrimerIndividual: this.props.showPrimerIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        hidePrimerIndividual: this.props.hidePrimerIndividual //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        annotationVisibility: annotationVisibility //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        featureLengthsToHide: this.props.featureLengthsToHide //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        primerLengthsToHide: this.props.primerLengthsToHide //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        partLengthsToHide: this.props.partLengthsToHide //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        sequence: sequence //we need to pass this in order to force the DT to rerenderannotationVisibility={annotationVisibility}
        ,
        noPadding: true,
        noFullscreenButton: true,
        onRowSelect: this.onRowSelect,
        selectedIds: selectedAnnotationId,
        formName: "annotationProperties",
        noRouter: true,
        isProtein: isProtein,
        keyedPartTags: (0, _teselagenReactComponents.getKeyedTagsAndTagOptions)(allPartTags),
        compact: true,
        isInfinite: true,
        schema: this.schema,
        entities: annotationsToUse
      }));
    };
    return AnnotationProperties;
  }(_react["default"].Component);
  return (0, _recompose.compose)((0, _withEditorProps.connectToEditor)(function (_ref5) {
    var _ref6;
    var readOnly = _ref5.readOnly,
      _ref5$annotationVisib = _ref5.annotationVisibility,
      annotationVisibility = _ref5$annotationVisib === void 0 ? {} : _ref5$annotationVisib,
      sequenceData = _ref5.sequenceData,
      selectionLayer = _ref5.selectionLayer,
      featureLengthsToHide = _ref5.featureLengthsToHide,
      primerLengthsToHide = _ref5.primerLengthsToHide,
      partLengthsToHide = _ref5.partLengthsToHide;
    return _ref6 = {
      annotationVisibility: annotationVisibility,
      selectionLayer: selectionLayer,
      readOnly: readOnly,
      featureLengthsToHide: featureLengthsToHide,
      primerLengthsToHide: primerLengthsToHide,
      partLengthsToHide: partLengthsToHide,
      sequenceData: sequenceData,
      sequence: sequenceData.sequence,
      annotations: sequenceData[annotationType + "s"]
    }, _ref6[annotationType + "s"] = sequenceData[annotationType + "s"], _ref6.sequenceLength = sequenceData.sequence.length, _ref6;
  }),
  // withEditorProps,
  (0, _teselagenReactComponents.withSelectedEntities)("annotationProperties"))(AnnotationProperties);
};
var _default = genericAnnotationProperties; // const ColorPickerPopover = ({ readOnly, onColorSelect, children }) => {
//   return (
//     <Popover
//       disabled={readOnly}
//       content={<ColorPicker onColorSelect={onColorSelect} />}
//     >
//       {children}
//     </Popover>
//   );
// };
exports["default"] = _default;
function getVisFilter(submenu) {
  return /*#__PURE__*/_react["default"].createElement(_teselagenReactComponents.DropdownButton, {
    style: {
      marginTop: 3
    },
    icon: "eye-open",
    className: "propertiesVisFilter",
    "data-tip": "\u8FC7\u6EE4\u5668\u53EF\u89C1",
    menu: /*#__PURE__*/_react["default"].createElement(_core.Menu, null, submenu)
  });
}