"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.TagsModalState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _bexCore = require("@wix/bex-core");
var _bi = require("@wix/bex-core/bi");
var _util = require("@wix/bex-core/util");
const actionOrigin = 'Manage Tags Modal';
class TagsModalState {
  constructor({
    tagsManagementState,
    entityTypeName
  }) {
    (0, _defineProperty2.default)(this, "tagsManagementState", void 0);
    (0, _defineProperty2.default)(this, "tagsSearchState", void 0);
    (0, _defineProperty2.default)(this, "manageTagsModalState", new _bexCore.ConditionalModalState());
    (0, _defineProperty2.default)(this, "confirmModalState", new _bexCore.ConditionalModalState());
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "tagsBIReporter", void 0);
    (0, _defineProperty2.default)(this, "entityTypeName", void 0);
    (0, _defineProperty2.default)(this, "origin", undefined);
    (0, _defineProperty2.default)(this, "tagSubOrigin", undefined);
    (0, _defineProperty2.default)(this, "editedTagId", null);
    (0, _defineProperty2.default)(this, "editedTagErrorMessage", null);
    (0, _defineProperty2.default)(this, "isShowingNewTagListItem", false);
    (0, _defineProperty2.default)(this, "tagToDelete", void 0);
    (0, _defineProperty2.default)(this, "toastConfigs", _mobx.observable.array([], {
      deep: false
    }));
    (0, _defineProperty2.default)(this, "ref", null);
    (0, _defineProperty2.default)(this, "handleCreateCtaTimeout", void 0);
    (0, _defineProperty2.default)(this, "showNotificationTimeout", void 0);
    (0, _defineProperty2.default)(this, "createTagFromListTimeout", void 0);
    (0, _defineProperty2.default)(this, "updateTagTimeout", void 0);
    this.tagsManagementState = tagsManagementState;
    this.tagsSearchState = new _bexCore.TagsSearchState({
      tagsManagementState
    });
    this.entityTypeName = entityTypeName;
    this.container = tagsManagementState.container;
    this.tagsBIReporter = new _bexCore.TagsBIReporter({
      collection: this.tagsManagementState.collection,
      reportBi: this.tagsManagementState.container.createBILogger({
        componentType: 'ManageTagsModal',
        ...tagsManagementState.fqdn
      }),
      location: 'Manage tags modal'
    });
    (0, _mobx.makeObservable)(this, {
      editedTagId: _mobx.observable,
      editedTagErrorMessage: _mobx.observable,
      isShowingNewTagListItem: _mobx.observable,
      init: _mobx.action,
      openManageTagsModal: _mobx.action,
      closeManageTagsModal: _mobx.action,
      handleSearchChange: _mobx.action,
      handleSearchClear: _mobx.action,
      handleCreateCtaClick: _mobx.action,
      handleEditCtaClick: _mobx.action,
      handleCancelEditCtaClick: _mobx.action,
      openConfirmDeleteModal: _mobx.action,
      createTagFromSearch: _mobx.action,
      createTagFromList: _mobx.action,
      updateTag: _mobx.action,
      deleteTag: _mobx.action,
      showNotification: _mobx.action,
      hideNotification: _mobx.action
    });
  }
  init() {
    const disposers = [(0, _util.addEventListener)(this.tagsManagementState.events, 'showToast', toastConfig => {
      this.showNotification(toastConfig);
    }), (0, _util.addEventListener)(this.tagsManagementState.events, 'hideToast', toastConfig => {
      this.hideNotification(toastConfig);
    }), () => {
      window.clearTimeout(this.handleCreateCtaTimeout);
      window.clearTimeout(this.showNotificationTimeout);
      window.clearTimeout(this.createTagFromListTimeout);
      window.clearTimeout(this.updateTagTimeout);
    }];
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  openManageTagsModal({
    origin,
    tagSubOrigin
  }) {
    this.origin = origin;
    this.tagSubOrigin = tagSubOrigin;
    this.manageTagsModalState.modal.open();
    this._reportBiModalOpened();
    this.tagsManagementState.overrideShowToast = true;
  }
  closeManageTagsModal() {
    this.editedTagId = null;
    this.editedTagErrorMessage = null;
    this.isShowingNewTagListItem = false;
    this.tagsSearchState.setSearchValue('');
    this._reportSearchEventsBi('blur');
    this.manageTagsModalState.modal.close();
    this._reportModalClosedBi();
    this.origin = undefined;
    this.tagsManagementState.overrideShowToast = false;
    this.hideNotification();
  }
  openConfirmDeleteModal(props) {
    this.confirmModalState.open({
      theme: 'destructive',
      primaryButtonText: this.container.translate('cairo.tags.manageTags.modal.deleteModal.delete.CTA'),
      secondaryButtonText: this.container.translate('cairo.tags.manageTags.modal.deleteModal.cancel.CTA'),
      title: this.container.translate('cairo.tags.manageTags.modal.deleteModal.title'),
      ...props
    });
  }
  handleSearchChange(newSearchValue) {
    this.editedTagId = null;
    this.isShowingNewTagListItem = false;
    this._reportSearchChangedBi(newSearchValue);
    this.tagsSearchState.setSearchValue(newSearchValue);
  }
  handleSearchClear() {
    this._reportSearchEventsBi('clear');
    this.tagsSearchState.setSearchValue('');
  }
  handleCreateCtaClick() {
    this.tagsSearchState.setSearchValue('');
    this.editedTagId = null;
    this.isShowingNewTagListItem = true;
    this.handleCreateCtaTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
  }
  handleEditCtaClick(tag) {
    this._reportSearchEventsBi('select');
    this.editedTagId = tag.id;
  }
  handleCancelEditCtaClick() {
    this.editedTagId = null;
    this.isShowingNewTagListItem = false;
  }
  showNotification(toastConfig) {
    this.toastConfigs.push(toastConfig);
    this.showNotificationTimeout = window.setTimeout(() => {
      this.hideNotification(toastConfig);
    }, 6000);
  }
  hideNotification(toastConfig) {
    if (toastConfig) {
      this.toastConfigs.remove(toastConfig);
    } else {
      this.toastConfigs.clear();
    }
  }
  async createTagFromSearch() {
    if (!this.searchValue || this.shownItems.length) {
      return;
    }
    const newName = this.searchValue.slice(0, _bexCore.TAG_MAX_LENGTH);
    this._reportSearchEventsBi('add');
    this._createTag({
      name: newName,
      isFromSearch: true,
      onSuccess: () => this._scrollContentTo('bottom')
    });
    this.tagsSearchState.setSearchValue('');
  }
  async createTagFromList(newName) {
    const {
      status,
      statusMessage
    } = this._isValidName(newName);
    if (status === 'error') {
      this.editedTagErrorMessage = statusMessage;
      this.createTagFromListTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
      return;
    }
    this._createTag({
      name: newName
    });
    this.isShowingNewTagListItem = false;
  }
  async updateTag({
    tag,
    newName,
    isLastTag
  }) {
    if (newName === tag.name) {
      this.editedTagId = null;
      return;
    }
    const {
      status,
      statusMessage
    } = this._isValidName(newName);
    if (status === 'error') {
      this.editedTagErrorMessage = statusMessage;
      if (isLastTag) {
        this.updateTagTimeout = window.setTimeout(() => this._scrollContentTo('bottom'), 100);
      }
      return;
    }
    this.editedTagId = null;
    const previousName = tag.name;
    const isFromSearch = this.tagsSearchState.searchValue !== '';
    this.tagsManagementState.updateTag({
      tagToUpdate: {
        ...tag,
        name: newName
      },
      previousName,
      isFromSearch,
      filteredListSize: this.shownItems.length,
      origin: actionOrigin,
      tagSubOrigin: this.tagSubOrigin,
      tagsBIReporter: this.tagsBIReporter,
      optimisticActionParams: {
        keepPosition: true,
        successToast: {
          biName: 'cairo-save-rename-tag-success',
          message: this.container.translate('cairo.tags.manageTags.modal.toast.rename.success')
        },
        showUndoToast: true,
        errorToast: error => {
          var _this$container$error, _this$container$error2;
          const resolvedError = (_this$container$error = (_this$container$error2 = this.container.errorHandler).getResolvedError) == null ? void 0 : _this$container$error.call(_this$container$error2, error);
          return {
            biName: 'cairo-save-rename-tag-error',
            message: (resolvedError == null ? void 0 : resolvedError.message) ?? this.container.translate('cairo.tags.manageTags.modal.toast.rename.error'),
            type: 'ERROR'
          };
        }
      }
    });
  }
  async deleteTag(tagToDelete) {
    this._reportSearchEventsBi('select');
    this.tagToDelete = tagToDelete;
    const isFromSearch = this.tagsSearchState.searchValue !== '';
    this.openConfirmDeleteModal({
      primaryButtonOnClick: async () => {
        this.tagsManagementState.deleteTag({
          tagToDelete,
          isFromSearch,
          filteredListSize: this.shownItems.length,
          origin: actionOrigin,
          tagSubOrigin: this.tagSubOrigin,
          tagsBIReporter: this.tagsBIReporter,
          optimisticActionParams: {
            successToast: {
              biName: 'cairo-delete-tag-success',
              message: this.container.translate('cairo.tags.manageTags.modal.toast.delete.success')
            },
            showUndoToast: true,
            errorToast: error => {
              var _this$container$error3, _this$container$error4;
              const resolvedError = (_this$container$error3 = (_this$container$error4 = this.container.errorHandler).getResolvedError) == null ? void 0 : _this$container$error3.call(_this$container$error4, error);
              return {
                biName: 'cairo-delete-tag-error',
                message: (resolvedError == null ? void 0 : resolvedError.message) ?? 'cairo.tags.manageTags.modal.toast.delete.error',
                type: 'ERROR'
              };
            }
          }
        });
      }
    });
  }
  get searchValue() {
    return this.tagsSearchState.searchValue;
  }
  get shownItems() {
    return this.tagsSearchState.filteredItems.sort((tag1, tag2) => new Date(tag1.createdDate).valueOf() - new Date(tag2.createdDate).valueOf());
  }
  get isOpen() {
    return this.manageTagsModalState.isOpen;
  }
  get toastConfig() {
    return this.toastConfigs[this.toastConfigs.length - 1] ?? null;
  }
  async _createTag({
    name,
    isFromSearch = false,
    onSuccess
  }) {
    this.tagsManagementState.createTag({
      name,
      isFromSearch,
      filteredListSize: this.shownItems.length,
      onSuccess,
      origin: actionOrigin,
      tagSubOrigin: this.tagSubOrigin,
      tagsBIReporter: this.tagsBIReporter,
      visualType: 'notification',
      optimisticActionParams: {
        successToast: {
          biName: 'cairo-save-new-tag-success',
          message: this.container.translate('cairo.tags.manageTags.modal.toast.create.success')
        },
        errorToast: error => {
          var _this$container$error5, _this$container$error6;
          const resolvedError = (_this$container$error5 = (_this$container$error6 = this.container.errorHandler).getResolvedError) == null ? void 0 : _this$container$error5.call(_this$container$error6, error);
          return {
            biName: 'cairo-save-new-tag-error',
            message: (resolvedError == null ? void 0 : resolvedError.message) ?? this.container.translate('cairo.tags.manageTags.modal.toast.create.error'),
            action: resolvedError == null ? void 0 : resolvedError.action
          };
        }
      }
    });
    this.editedTagErrorMessage = null;
  }
  _isValidName(tagName) {
    if (tagName.length === 0) {
      return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.emptyName'));
    }
    if (tagName.length > _bexCore.TAG_MAX_LENGTH) {
      return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.maxLength', {
        count: _bexCore.TAG_MAX_LENGTH
      }));
    }
    if (this.tagsManagementState.items.find(({
      name
    }) => name.toLowerCase() === tagName.toLowerCase())) {
      return this._getValidationMessage(this.container.translate('cairo.tags.manageTags.modal.list.input.validation.exists'));
    }
    return {
      status: '',
      statusMessage: ''
    };
  }
  _reportBiModalOpened() {
    var _this$tagsManagementS;
    this.tagsBIReporter.reportBi((0, _bi.cairoTagsModalStartLoad)({
      numTags: (_this$tagsManagementS = this.tagsManagementState.items) == null ? void 0 : _this$tagsManagementS.length,
      origin: this.origin
    }));
  }
  _reportModalClosedBi() {
    this.tagsBIReporter.onModalClose({
      origin: this.origin
    });
  }
  _reportSearchChangedBi(searchValue) {
    if (searchValue !== '') {
      this.tagsBIReporter.onSearch(searchValue);
    } else {
      this.tagsBIReporter._clearAllEvents();
    }
  }
  _reportSearchEventsBi(event) {
    return this.tagsBIReporter.events.emit(event);
  }
  _scrollContentTo(direction = 'top') {
    var _this$ref, _this$ref2;
    (_this$ref = this.ref) == null || (_this$ref = _this$ref.current) == null || _this$ref.scrollTo({
      top: direction === 'top' ? 0 : (_this$ref2 = this.ref) == null || (_this$ref2 = _this$ref2.current) == null ? void 0 : _this$ref2.scrollHeight,
      behavior: 'smooth'
    });
  }
  _getValidationMessage(statusMessage) {
    return {
      status: 'error',
      statusMessage
    };
  }
}
exports.TagsModalState = TagsModalState;
//# sourceMappingURL=TagsModalState.js.map