import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import './DataFetcher.js';
import './ISave.js';
import '@sankhyalabs/core';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher.js';
import './filter-item-type.enum.js';
import { F as FormConfigFetcher } from './form-config-fetcher.js';
import './constants.js';

const snkSimpleFormConfigCss = ":host{display:block}.config-container{display:flex;flex-direction:column;align-items:center;justify-content:space-between}.config-lists{width:100%;margin-bottom:12px}.config-actions{display:flex;flex-direction:row;justify-content:flex-end;width:100%;gap:12px}";

const SnkSimpleFormConfig = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.snkConfigSaved = createEvent(this, "snkConfigSaved", 7);
    this._formConfigFetcher = new FormConfigFetcher();
    this.fieldsToSave = [];
    this.dataUnit = undefined;
    this.configName = undefined;
    this.messagesBuilder = undefined;
    this.avaliableFields = [];
    this.selectedFields = [];
  }
  /**
   * Responsável por abrir o configurador.
   */
  async show() {
    var _a;
    await ((_a = this.ezDoubleListRef) === null || _a === void 0 ? void 0 : _a.resetSelectedLists());
    await this.initializeFormConfig();
    this.ezPopupRef.opened = true;
  }
  ;
  async initializeFormConfig() {
    if (!this.configName)
      return;
    const allFields = this.getAllVisibleFieldsFromDataUnit();
    const displayedFieldNameList = await this.getConfig();
    //Quando não retorna dados, é por quê não existe configuração do usuário salva.
    if (displayedFieldNameList.length === 0) {
      this.avaliableFields = [];
      this.selectedFields = [...allFields];
      this.fieldsToSave = [...this.selectedFields];
      return;
    }
    const selectedFieldsAux = this.sortDisplayedFields(displayedFieldNameList, allFields);
    const avaliableFieldsAux = allFields.filter(field => !displayedFieldNameList.includes(field.id));
    this.avaliableFields = [...avaliableFieldsAux];
    this.selectedFields = [...selectedFieldsAux];
    this.fieldsToSave = [...this.selectedFields];
  }
  async getConfig() {
    const fieldList = await this._formConfigFetcher.fetchSimpleFormConfig(this.configName);
    return [...this.removeDuplicates(fieldList)];
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  removeDuplicates(strings) {
    return strings.filter((item, index) => strings.indexOf(item) === index);
  }
  sortDisplayedFields(displayedFieldNameList, allFields) {
    const selectedFieldsAux = [];
    //É preciso garantir a ordem na qual os campos vieram na resposta do fetchSimpleFormConfig.
    displayedFieldNameList.forEach(fieldName => {
      const field = allFields.find(field => field.id === fieldName);
      if (!field)
        return;
      selectedFieldsAux.push(field);
    });
    return selectedFieldsAux;
  }
  getAllVisibleFieldsFromDataUnit() {
    var _a, _b, _c;
    const visibleFields = ((_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.fields) !== null && _c !== void 0 ? _c : []).filter(field => field.visible);
    return visibleFields.map(field => {
      return { id: field.name, label: field.label };
    });
  }
  close() {
    this.ezPopupRef.opened = false;
  }
  async handleResetConfigs() {
    await this._formConfigFetcher.restoreFormConfig(this.configName);
    await this.initializeFormConfig();
    await this.handleSave();
  }
  handleCancel() {
    this.close();
  }
  async handleSave() {
    const saveList = this.fieldsToSave.map(field => field.id);
    await this._formConfigFetcher.saveSimpleFormConfig(this.configName, saveList);
    this.close();
    this.snkConfigSaved.emit();
  }
  render() {
    return (h("ez-popup", { ref: (ref) => this.ezPopupRef = ref, heightMode: 'auto', size: 'medium', ezTitle: this.getMessage("snkSimpleFormConfig.popup.title") }, h("div", { class: 'config-container' }, h("div", { class: 'config-lists' }, h("ez-double-list", { ref: (ref) => this.ezDoubleListRef = ref, leftList: this.avaliableFields, leftTitle: this.getMessage("snkSimpleFormConfig.lists.availableFields"), rightList: this.selectedFields, rightTitle: this.getMessage("snkSimpleFormConfig.lists.selectedFields"), onEzRightListChanged: ({ detail }) => this.fieldsToSave = [...detail], entityLabel: this.getMessage("snkSimpleFormConfig.lists.entityLabel"), entityLabelPlural: this.getMessage("snkSimpleFormConfig.lists.entityLabelPlural") })), h("div", { class: 'config-actions' }, h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.restore"), onClick: this.handleResetConfigs.bind(this), size: 'small' }), h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.cancel"), onClick: this.handleCancel.bind(this), size: 'small' }), h("ez-button", { label: this.getMessage("snkSimpleFormConfig.buttons.save"), class: 'ez-button--primary', onClick: this.handleSave.bind(this), size: 'small' })))));
  }
  static get style() { return snkSimpleFormConfigCss; }
}, [0, "snk-simple-form-config", {
    "dataUnit": [16],
    "configName": [1, "config-name"],
    "messagesBuilder": [16],
    "avaliableFields": [32],
    "selectedFields": [32],
    "show": [64]
  }]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-simple-form-config"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkSimpleFormConfig);
      }
      break;
  } });
}

export { SnkSimpleFormConfig as S, defineCustomElement as d };
