import { ArrayUtils, ObjectUtils } from '@sankhyalabs/core';
import { ApplicationUtils } from '@sankhyalabs/ezui/dist/collection/utils';
import { h } from '@stencil/core';
import Sortable from 'sortablejs';
import { TAB_NAMES } from '../../../lib/utils/constants';
export class GuidesConfigurator {
  constructor() {
    this.ID_VISIBLE_GUIDES = 'container-visible-guides';
    this.ID_HIDDEN_GUIDES = 'container-hidden-guides';
    this.sortLogic = (a, b) => {
      var _a, _b;
      const orderA = (_a = a.order) !== null && _a !== void 0 ? _a : Number.MAX_VALUE;
      const orderB = (_b = b.order) !== null && _b !== void 0 ? _b : Number.MAX_VALUE;
      return orderA - orderB;
    };
    this.mainGuide = undefined;
    this.filterTerm = '';
    this.visibleGuides = [];
    this.hiddenGuides = [];
    this.guidesList = [];
    this.selectedGuide = undefined;
    this.messagesBuilder = undefined;
  }
  onMessagesBuilderChange() {
    this.setCustomCSSProperties();
  }
  observeVisibleGuides(newGuides) {
    this.initGuidesConfig(newGuides);
  }
  observeSelectedGuide(newGuide) {
    this.guideSelected.emit(newGuide);
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  initGuidesConfig(newGuides) {
    const visibleAux = [...newGuides.filter(guide => (guide.visible && guide.name !== TAB_NAMES.main))];
    const hiddenAux = [...newGuides.filter(guide => (!guide.visible && guide.name !== TAB_NAMES.main))];
    this.visibleGuides = [...visibleAux.sort(this.sortLogic)];
    this.hiddenGuides = [...hiddenAux.sort(this.sortLogic)];
    this.mainGuide = newGuides.find(g => g.name === TAB_NAMES.main);
  }
  handleAddGuide() {
    this.createNewGuide.emit();
  }
  handleSelectGuide(guide, evt) {
    evt.stopPropagation();
    this.selectedGuide = guide;
  }
  toggleGuideVisibility(guide, evt) {
    evt.stopPropagation();
    const updatedGuide = Object.assign(Object.assign({}, guide), { visible: !guide.visible });
    let visibleAux;
    let hiddenAux;
    if (guide.visible) {
      visibleAux = [...this.visibleGuides.filter(g => g.name !== guide.name)];
      hiddenAux = [...this.hiddenGuides, updatedGuide];
    }
    else {
      visibleAux = [...this.visibleGuides, updatedGuide];
      hiddenAux = [...this.hiddenGuides.filter(g => g.name !== guide.name)];
    }
    const updatedGuideList = [...visibleAux, ...hiddenAux];
    this.applyGuidesUpdate(updatedGuideList);
  }
  adjustListOrder(guideList) {
    return guideList.map((g, index) => {
      return Object.assign(Object.assign({}, g), { order: index });
    });
  }
  applyGuidesUpdate(updatedGuideList) {
    let newGuidesList = this.adjustListOrder(updatedGuideList);
    newGuidesList = [this.mainGuide, ...newGuidesList];
    if (!ObjectUtils.equals(newGuidesList, this.guidesList)) {
      this.guideListChanged.emit(newGuidesList);
    }
  }
  async handleDeleteGuide(guide, e) {
    e.stopPropagation();
    const title = this.getMessage('snkFormConfig.confirm.title');
    const message = this.getMessage('snkFormConfig.confirm.deleteGuide').replace('{0}', guide.label);
    const canRemove = await ApplicationUtils.confirm(title, message);
    if (!canRemove)
      return;
    this.guideDeleted.emit(guide);
    const deletedMessage = this.getMessage('snkFormConfig.info.successfullyGuideDeleted').replace('{0}', guide.label);
    ApplicationUtils.info(deletedMessage);
  }
  renderItems(guides) {
    const guidesToShow = ArrayUtils.applyStringFilter(this.filterTerm, guides);
    return guidesToShow.map(guide => {
      var _a;
      return (h("div", { key: guide.name, "data-guide-name": guide.name, title: guide.label, class: `guide-item ${((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.label) === guide.label ? 'selected' : ''} ${this.filterTerm.length ? 'disable-sort' : ''}`, onClick: e => this.handleSelectGuide(guide, e) }, h("span", null, h("ez-icon", { iconName: "drag-indicator", class: 'ez-margin-right--small' })), h("span", { class: 'item-label' }, guide.label), h("div", { class: 'actions' }, h("ez-button", { mode: "icon", class: "ez-button--tertiary", onClick: e => this.toggleGuideVisibility(guide, e), size: "medium", iconName: guide.visible ? 'eye-off' : 'eye', title: guide.visible ?
          this.getMessage('snkFormConfig.guidesConfigurator.actions.hide') :
          this.getMessage('snkFormConfig.guidesConfigurator.actions.show') }), h("ez-button", { mode: "icon", class: "ez-button--tertiary", onClick: e => this.handleDeleteGuide(guide, e), size: "medium", isDisabled: guide.isCustom || guide.isDetail, iconName: 'delete', title: guide.isCustom || guide.isDetail ?
          this.getMessage('snkFormConfig.guidesConfigurator.canNotDeleteCustomGuide') :
          this.getMessage('snkFormConfig.guidesConfigurator.actions.delete') }))));
    });
  }
  getContainerElement(id) {
    return this.el.querySelector(`[id="${id}"]`);
  }
  handleSortGuide() {
    const updatedGuideList = [...this.getGuidesFromStatus(true), ...this.getGuidesFromStatus(false)];
    this.applyGuidesUpdate(updatedGuideList);
  }
  getGuidesFromStatus(visible) {
    let updatedGuideList = [];
    const orderedGuides = this.getOrderedGuideNames(visible ? this.ID_VISIBLE_GUIDES : this.ID_HIDDEN_GUIDES);
    orderedGuides.forEach(guideName => {
      const updatedGuide = this.guidesList.find(g => g.name === guideName);
      if (updatedGuide) {
        updatedGuideList.push(Object.assign(Object.assign({}, updatedGuide), { visible }));
      }
    });
    return updatedGuideList;
  }
  getOrderedGuideNames(containerId) {
    var _a;
    const guidesCollection = (_a = this.getContainerElement(containerId)) === null || _a === void 0 ? void 0 : _a.children;
    return Array.from(guidesCollection).map((element) => element.getAttribute('data-guide-name'));
  }
  initializeDraggableContainers() {
    this._sortableVisibleGuides = new Sortable(this.getContainerElement(this.ID_VISIBLE_GUIDES), {
      group: 'guides',
      ghostClass: 'ghost',
      direction: 'vertical',
      filter: '.disable-sort',
      animation: 15,
      onSort: () => this.handleSortGuide(),
    });
    this._sortableInvisibleGuides = new Sortable(this.getContainerElement(this.ID_HIDDEN_GUIDES), {
      group: 'guides',
      ghostClass: 'ghost',
      animation: 15,
      filter: '.disable-sort',
      onSort: () => this.handleSortGuide(),
    });
  }
  handleSelectMainGuide() {
    this.guideSelected.emit(this.mainGuide);
  }
  setCustomCSSProperties() {
    document.documentElement.style.setProperty('--no-hidden-guides-message', `"${this.getMessage('snkFormConfig.guidesConfigurator.noHiddenGuides')}"`);
    document.documentElement.style.setProperty('--no-visible-guides-message', `"${this.getMessage('snkFormConfig.guidesConfigurator.noVisibleGuides')}"`);
  }
  componentDidLoad() {
    this.initializeDraggableContainers();
    this.initGuidesConfig(this.guidesList);
    this.setCustomCSSProperties();
  }
  render() {
    var _a, _b, _c;
    return (h("ez-sidebar-navigator", { class: 'ezSidebarNavigator', type: 'fixed', size: 'md', titleMenu: this.getMessage('snkFormConfig.guidesConfigurator.title') }, h("div", { class: 'navigator-container' }, h("ez-filter-input", { slot: "content", mode: "slim", label: this.getMessage('snkFormConfig.guidesConfigurator.searchGuide'), onEzChange: evt => this.filterTerm = evt.detail }), h("div", { onClick: this.handleSelectMainGuide.bind(this), class: `main-guide ${((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name) === ((_b = this.mainGuide) === null || _b === void 0 ? void 0 : _b.name) ? 'selected' : ''}` }, h("span", null, (_c = this.mainGuide) === null || _c === void 0 ? void 0 : _c.label)), h("div", { class: 'collapsible-container' }, h("div", { class: 'collapsible-item' }, h("ez-collapsible-box", { label: this.getMessage('snkFormConfig.guidesConfigurator.visibleGuides'), headerSize: "large" }, h("div", { id: this.ID_VISIBLE_GUIDES, class: `guide-list ${!this.visibleGuides.length ? 'visible-empty-content' : ''}` }, this.renderItems(this.visibleGuides)))), h("div", { class: 'collapsible-item' }, h("ez-collapsible-box", { label: this.getMessage('snkFormConfig.guidesConfigurator.hiddenGuides'), headerSize: "large" }, h("div", { id: this.ID_HIDDEN_GUIDES, class: `guide-list ${!this.hiddenGuides.length ? 'hidden-empty-content' : ''}` }, this.renderItems(this.hiddenGuides))))), h("div", { class: 'add-button-container', onClick: this.handleAddGuide.bind(this) }, h("ez-icon", { slot: "leftIcon", iconName: "plus" }), h("span", null, this.getMessage('snkFormConfig.guidesConfigurator.createNewGuide'))))));
  }
  static get is() { return "guides-configurator"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["guides-configurator.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["guides-configurator.css"]
    };
  }
  static get properties() {
    return {
      "guidesList": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IGuideConfig[]",
          "resolved": "IGuideConfig[]",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "selectedGuide": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      }
    };
  }
  static get states() {
    return {
      "mainGuide": {},
      "filterTerm": {},
      "visibleGuides": {},
      "hiddenGuides": {}
    };
  }
  static get events() {
    return [{
        "method": "guideSelected",
        "name": "guideSelected",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "guideListChanged",
        "name": "guideListChanged",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig[]",
          "resolved": "IGuideConfig[]",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "guideDeleted",
        "name": "guideDeleted",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IGuideConfig",
          "resolved": "IGuideConfig",
          "references": {
            "IGuideConfig": {
              "location": "import",
              "path": "../FormConfigHelper"
            }
          }
        }
      }, {
        "method": "createNewGuide",
        "name": "createNewGuide",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get elementRef() { return "el"; }
  static get watchers() {
    return [{
        "propName": "messagesBuilder",
        "methodName": "onMessagesBuilderChange"
      }, {
        "propName": "guidesList",
        "methodName": "observeVisibleGuides"
      }, {
        "propName": "selectedGuide",
        "methodName": "observeSelectedGuide"
      }];
  }
}
