"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.TagsFormState = exports.MANAGE_TAGS_OPTION_ID = exports.ADD_ITEM_OPTION_ID = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _v = require("@wix/bex-utils/@wix/bi-logger-os-data/v2");
var _TagsManagementState = require("./TagsManagementState");
var _TagsSearchState = require("./TagsSearchState");
var _TagsAssignmentState = require("./TagsAssignmentState");
var _TagsBIReporter = require("./TagsBIReporter");
const ADD_ITEM_OPTION_ID = exports.ADD_ITEM_OPTION_ID = 'add-item-option';
const MANAGE_TAGS_OPTION_ID = exports.MANAGE_TAGS_OPTION_ID = 'manage-tags-option';
class TagsFormState {
  constructor({
    tagsManagementState,
    origin,
    initialTags
  }) {
    (0, _defineProperty2.default)(this, "tagsAssignmentState", void 0);
    (0, _defineProperty2.default)(this, "tagsManagementState", void 0);
    (0, _defineProperty2.default)(this, "tagsSearchState", void 0);
    (0, _defineProperty2.default)(this, "tagsBIReporter", void 0);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "origin", void 0);
    (0, _defineProperty2.default)(this, "entityId", void 0);
    (0, _defineProperty2.default)(this, "previousSearchValue", '');
    (0, _defineProperty2.default)(this, "isMultiSelectOnFocus", false);
    (0, _defineProperty2.default)(this, "assignOptimisticActionParams", tagName => ({
      onError: error => {
        this.tagsBIReporter.onError({
          tagName,
          actionName: 'Assign tag',
          origin: this.origin
        }, error);
      },
      errorToast: () => {
        return {
          biName: 'cairo-assign-tag-error',
          message: this.container.translate('cairo.tags.collectionPage.toast.update.error')
        };
      },
      onTryAgain: () => {
        this.tagsBIReporter.onTryAgain({
          actionName: 'Assign tag'
        });
      }
    }));
    (0, _defineProperty2.default)(this, "assignTag", async (tag, onSubmit) => {
      this.tagsAssignmentState.assignTag({
        tag,
        onSubmit,
        isFromSearch: this.previousSearchValue !== '',
        optimisticActionParams: this.assignOptimisticActionParams(tag.name)
      });
    });
    (0, _defineProperty2.default)(this, "unassignTag", async (tagId, onSubmit) => {
      const tagToUnassign = this.tagsAssignmentState.assignedTags.find(tag => tag.id === tagId);
      if (tagToUnassign) {
        this.tagsAssignmentState.unassignTag({
          tag: tagToUnassign,
          onSubmit,
          isFromSearch: false,
          optimisticActionParams: {
            errorToast: () => {
              return {
                biName: 'cairo-remove-assign-tag-error',
                message: this.container.translate('cairo.tags.collectionPage.toast.update.error')
              };
            },
            onError: error => {
              this.tagsBIReporter.onError({
                tagName: tagToUnassign.name,
                actionName: 'Remove assign tag',
                origin: this.origin
              }, error);
            },
            onTryAgain: () => {
              this.tagsBIReporter.onTryAgain({
                actionName: 'Remove assign tag'
              });
            }
          }
        });
      }
    });
    (0, _defineProperty2.default)(this, "createAndAssignTag", async (name, onSubmit) => {
      this.tagsAssignmentState.createAndAssignTag({
        name,
        onSubmit,
        filteredListSize: this.displayedTagOptions.length,
        createOptimisticActionParams: {
          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-new-tag-error',
              message: (resolvedError == null ? void 0 : resolvedError.message) ?? this.container.translate('cairo.tags.collectionPage.toast.create.error'),
              action: resolvedError == null ? void 0 : resolvedError.action
            };
          }
        },
        assignOptimisticActionParams: this.assignOptimisticActionParams(name)
      });
    });
    (0, _defineProperty2.default)(this, "validate", async () => {
      const tags = {
        privateTags: {
          tagIds: this.tagsAssignmentState.assignedTagIds
        }
      };
      return {
        isValid: true,
        tags,
        values: tags
      };
    });
    this.container = tagsManagementState.container;
    this.origin = origin;
    this.tagsManagementState = tagsManagementState;
    this.tagsBIReporter = new _TagsBIReporter.TagsBIReporter({
      collection: this.tagsManagementState.collection,
      reportBi: this.container.createBILogger({
        componentType: 'TagsWidget',
        ...tagsManagementState.fqdn
      }),
      location: 'Tags widget'
    });
    this.tagsAssignmentState = new _TagsAssignmentState.TagsAssignmentState({
      initialTags,
      tagsManagementState: this.tagsManagementState,
      tagsBIReporter: this.tagsBIReporter,
      origin,
      fqdn: tagsManagementState.fqdn
    });
    this.tagsSearchState = new _TagsSearchState.TagsSearchState({
      tagsManagementState: this.tagsManagementState
    });
    (0, _mobx.makeObservable)(this, {
      init: _mobx.action,
      previousSearchValue: _mobx.observable,
      isMultiSelectOnFocus: _mobx.observable,
      displayedAssignedTags: _mobx.computed,
      displayedTagOptions: _mobx.computed,
      isDirty: _mobx.computed,
      handleManageTagsCtaClick: _mobx.action,
      handleSearchChange: _mobx.action,
      handleOptionsShow: _mobx.action,
      setIsMultiSelectOnFocus: _mobx.action
    });
  }
  init({
    entityId
  }) {
    this.entityId = entityId;
    const disposers = [this.tagsAssignmentState.init({
      entityId
    })];
    this.tagsBIReporter.reportBi((0, _v.cairoTagsWidgetLoaded)({
      itemId: this.entityId ?? undefined,
      numTags: this.tagsManagementState.items.length,
      numTagsAssigned: this.tagsAssignmentState.initialTagIds.length
    }));
    return () => {
      disposers.forEach(disposer => disposer == null ? void 0 : disposer());
    };
  }
  get displayedAssignedTags() {
    return this.tagsAssignmentState.assignedTags.map(assignedTag => ({
      id: assignedTag.id,
      label: assignedTag.name
    }));
  }
  get displayedTagOptions() {
    return this.tagsSearchState.items.filter(tag => !this.displayedAssignedTags.find(assignedTag => assignedTag.label === tag.name)).map(tag => {
      return {
        id: tag.id,
        value: tag.name
      };
    });
  }
  get isInEmptyState() {
    return this.tagsManagementState.items.length === 0;
  }
  get searchValue() {
    return this.tagsSearchState.searchValue;
  }
  get shouldShowCreateTagOption() {
    return this.searchValue && !this.tagsSearchState.hasSameTagAsSearch;
  }
  handleTagSelect(option, onSubmit) {
    if (option.id === ADD_ITEM_OPTION_ID) {
      this._invokeBiOnCtaClick('Create tags');
      const tagName = this.previousSearchValue.slice(0, _TagsManagementState.TAG_MAX_LENGTH);
      this.createAndAssignTag(tagName, onSubmit);
      return;
    }
    this.assignTag({
      id: option.id,
      name: option.value
    }, onSubmit);
  }
  handleManageTagsCtaClick() {
    this._invokeBiOnCtaClick('Manage tags');
  }
  handleSearchChange(newSearchValue) {
    this.previousSearchValue = this.searchValue;
    this.tagsSearchState.setSearchValue(newSearchValue);
  }
  handleOptionsShow() {
    this._invokeBiOnCtaClick('Assign tags');
  }
  setIsMultiSelectOnFocus(isOnFocusValue) {
    this.isMultiSelectOnFocus = isOnFocusValue;
  }
  get isDirty() {
    return this.tagsAssignmentState.isDirty;
  }
  _invokeBiOnCtaClick(actionName) {
    return this.tagsBIReporter.reportBi((0, _v.cairoTagsWidgetClickOnCta)({
      itemId: this.entityId ?? undefined,
      numTags: this.tagsManagementState.items.length,
      numTagsAssigned: this.tagsAssignmentState.assignedTags.length,
      actionName
    }));
  }
}
exports.TagsFormState = TagsFormState;
//# sourceMappingURL=TagsFormState.js.map