import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { ApplicationContext, StringUtils, ElementIDUtils } from '@sankhyalabs/core';
import { ApplicationUtils, DialogType } from '@sankhyalabs/ezui/dist/collection/utils';
import { C as ConfigStorage } from './ConfigStorage.js';
import { O as ORDER_VALUES } from './constants.js';
import { d as defineCustomElement$1 } from './snk-select-box2.js';

const snkGridConfigCss = ".sc-snk-grid-config-h{--snk-grid-config__footer--padding-top:var(--space--medium, 12px);--snk-grid-config__main--padding-right:var(--space--medium, 12px);--snk-grid-config__tabselector-container--padding:var(--space--medium, 12px);--snk-grid-config__button-close--padding-left:var(--space--medium, 12px);--snk-grid-config__title--color:var(--title--primary, #2B3A54);--snk-grid-config__title--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__title--font-size:var(--title--large, 20px);--snk-grid-config__title--font-weight:var(--text-weight--extra-large, 700);--snk-grid-config__subtitle--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__subtitle--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-family:var(--font-pattern, \"Roboto\");--snk-grid-config__group--font-size:var(--text--medium, 14px);--snk-grid-config__group--font-weight:var(--text-weight--large, 600);--snk-grid-config__group--padding-bottom:var(--space-small, 6px);--snk-grid-config__scrollbar--color-default:var(--scrollbar--default, #626e82);--snk-grid-config__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--snk-grid-config__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--snk-grid-config__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--snk-grid-config__scrollbar--border-radius:var(--border--radius-small, 6px);--snk-grid-config__scrollbar--width:var(--space--small, 6px);display:flex;flex-direction:column;max-height:100%;width:100%}.grid-config__body.sc-snk-grid-config{overflow:auto}.padding-right--medium.sc-snk-grid-config{padding-right:var(--space--medium)}ez-list.sc-snk-grid-config{height:100%}.height-calc.sc-snk-grid-config{max-height:calc(100% - 24px)}.grid-config__footer.sc-snk-grid-config{display:flex;justify-content:flex-end;width:100%;padding-top:var(--snk-grid-config__footer--padding-top)}.hidden.sc-snk-grid-config{display:none}.tabselector-container.sc-snk-grid-config{padding:var(--snk-grid-config__tabselector-container--padding) 0}.button-close.sc-snk-grid-config{padding-left:var(--snk-grid-config__button-close--padding-left)}.title-container.sc-snk-grid-config{display:flex;justify-content:space-between;align-items:center;width:100%}.title.sc-snk-grid-config{display:flex;margin:0;line-height:normal;letter-spacing:0em;text-align:left;color:var(--snk-grid-config__title--color);font-size:var(--snk-grid-config__title--font-size);font-family:var(--snk-grid-config__title--font-family);font-weight:var(--snk-grid-config__title--font-weight)}.subtitle.sc-snk-grid-config{color:var(--text--primary);font-size:var(--snk-grid-config__subtitle--font-size);font-family:var(--snk-grid-config__subtitle--font-family)}.grid-config__main.sc-snk-grid-config{overflow-y:auto;scrollbar-width:thin;width:100%;padding-bottom:20px;scrollbar-color:var(--snk-grid-config__scrollbar--color-clicked) var(--snk-grid-config__scrollbar--color-background)}.group-name.sc-snk-grid-config{font-family:var(--snk-grid-config__group--font-family);font-size:var(--snk-grid-config__group--font-size);font-weight:var(--snk-grid-config__group--font-weight);padding-bottom:var(--snk-grid-config__group--padding-bottom)}";

const SnkGridConfig = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.configChange = createEvent(this, "configChange", 7);
    this.configCancel = createEvent(this, "configCancel", 7);
    this._orderListItems = [];
    this._orderPriorityList = [];
    this._visibleList = [];
    this._hiddenList = [];
    this._columListItems = [];
    this._dataChanged = false;
    this._componenteInternalKey = Date.now();
    this.selectedIndex = 0;
    this.columns = undefined;
    this.config = undefined;
    this.configName = undefined;
    this.resourceID = undefined;
    this._collapsibleBoxListOrder = true;
    this._collapsibleBoxListSelect = false;
  }
  /* Creation Methods */
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-grid.msg.ts"
   */
  getMessage(key, params) {
    const application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    return application.messagesBuilder.getMessage(key, params);
  }
  getSortableColumns() {
    let newList = [];
    this.columns.filter(col => { var _a; return StringUtils.getBooleanValue((_a = col === null || col === void 0 ? void 0 : col.props) === null || _a === void 0 ? void 0 : _a.get('sortable'), true); }).forEach((column) => {
      var _a, _b;
      let configItem = (_a = this.config) === null || _a === void 0 ? void 0 : _a.columns.find((item) => item.name === column.name);
      let item = { label: column.label, sort: (_b = column === null || column === void 0 ? void 0 : column.sort) !== null && _b !== void 0 ? _b : ORDER_VALUES.asc.value, id: column.name };
      if (configItem) {
        item['orderIndex'] = configItem.orderIndex;
        item['ascending'] = configItem.ascending;
      }
      if (!column.hidden) {
        newList.push(item);
      }
    });
    return newList;
  }
  createOrderList() {
    var _a;
    let newSortableList = this.getSortableColumns();
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      const orderedList = [];
      this._orderPriorityList.forEach((priorityItem) => {
        const item = newSortableList.find(col => col.id === priorityItem.id);
        if (item) {
          orderedList.push(item);
        }
      });
      newSortableList.forEach(item => {
        if (!orderedList.find(o => o.id === item.id)) {
          orderedList.push(item);
        }
      });
      this._orderListItems = orderedList;
    }
    else {
      newSortableList.sort((a, b) => {
        //OS dois tem order index 0 e pelo menos um deles tem orientação de ordenação.
        if (a.orderIndex == 0 && b.orderIndex == 0 && (a.ascending != undefined || b.ascending != undefined)) {
          if (a.ascending != undefined)
            return -1;
          if (b.ascending != undefined)
            return 1;
          return 0;
          //Pelo menos um deles tem order index diferente de 0 e os dois tem orientação de ordenação.
        }
        else if (a.ascending != undefined && b.ascending != undefined) {
          return (a.orderIndex - b.orderIndex);
          //Pelo menos um deles tem order index diferente de 0 e pelo menos um deles tem orientação de ordenação.
        }
        else if (a.ascending != undefined || b.ascending != undefined) {
          if (a.ascending != undefined)
            return -1;
          if (b.ascending != undefined)
            return 1;
          return 0;
        }
        return (a.orderIndex - b.orderIndex);
      });
      this._orderListItems = newSortableList;
    }
  }
  createColumnList() {
    const visibleGroup = this.buildVisibleGroup();
    const hiddenGroup = this.buildHiddenGroup();
    this.columns.forEach(column => {
      const item = this.buildListItemFromColumn(column);
      if (column.hidden) {
        hiddenGroup.items.push(item);
      }
      else {
        visibleGroup.items.push(item);
      }
    });
    this._columListItems = [visibleGroup, hiddenGroup];
    this._visibleList = visibleGroup.items;
    this._hiddenList = hiddenGroup.items;
    this.createOrderList();
  }
  buildVisibleGroup() {
    return {
      group: this.getMessage('snkGridConfig.group.visible'),
      items: [],
    };
  }
  buildHiddenGroup() {
    return {
      group: this.getMessage('snkGridConfig.group.hidden'),
      items: [],
      sort: ORDER_VALUES.asc.value,
    };
  }
  createOrderListSlotDataElementId(item) {
    var _a;
    return `${this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME)}_configItem_${StringUtils.toCamelCase((_a = item.id) !== null && _a !== void 0 ? _a : item.label)}`;
  }
  buildOrderListSlot(item) {
    const dataElementId = this.createOrderListSlotDataElementId(item);
    let selectedOption = ORDER_VALUES.none.value;
    if ((item === null || item === void 0 ? void 0 : item.ascending) != undefined) {
      selectedOption = item.ascending == true ? ORDER_VALUES.asc.value : ORDER_VALUES.desc.value;
    }
    return (h("snk-select-box", { selectedOption: selectedOption, key: 'snk-select-box-' + this._componenteInternalKey + '-' + item, "data-element-id": dataElementId, onEzChange: (evt) => {
        evt.stopPropagation();
        this.updateOrder(evt.detail, item.id);
      }, preventAutoFocus: true }));
  }
  updateOrder(sortOrder, updatedItemId) {
    var _a;
    this._dataChanged = true;
    let newList = [...this.columns];
    let newItem = newList.find((item) => item.name === updatedItemId);
    if (newItem) {
      newItem.sort = sortOrder.value === ORDER_VALUES.none.value ? undefined : sortOrder.value;
    }
    let orderArray;
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      const priorityItem = this._orderPriorityList.find((item) => item.id === newItem.name);
      if (priorityItem) {
        priorityItem.sort = sortOrder.value === ORDER_VALUES.none.value ? undefined : sortOrder.value;
      }
      this._orderPriorityList.filter((item) => item.sort != undefined).forEach((item, index) => {
        if (item.id === newItem.name) {
          newItem.sortIndex = index;
        }
      });
    }
    else {
      orderArray = newList.filter((item) => item.sort && item.hidden !== true)
        .map((item, index) => {
        return { name: item.name, orderIndex: index };
      });
      orderArray.forEach((element) => {
        newList.find((item) => item.name === element.name).sortIndex = element.orderIndex;
      });
    }
    this.columns = newList;
  }
  finish() {
    if (!this._dataChanged) {
      this.closeConfig();
      return;
    }
    this.updateColumns();
    this._dataChanged = false;
    this.closeConfig();
    this.save();
    this._orderPriorityList = [];
  }
  updateColumns() {
    this.columns = this._columListItems.flatMap((group) => group.items.map((item) => this.buildColumnFromListItem(item, group)));
  }
  buildColumnFromListItem(item, group) {
    const baseColumn = this.columns.find((column) => column.name === item.id);
    if (!baseColumn) {
      throw new Error(`Column with name "${item.id}" not found.`);
    }
    return Object.assign(Object.assign({}, baseColumn), { hidden: group.group === this.getMessage('snkGridConfig.group.hidden') });
  }
  saveGridConfigOnStorage(_newConfig) {
    ConfigStorage.saveGridConfig(_newConfig, this.configName, this.resourceID)
      .then((savedConfig) => {
      this.configChange.emit(savedConfig);
      ApplicationUtils.info(this.getMessage('snkGridConfig.info.successfullyConfigSaved'), { iconName: 'check' });
    });
  }
  reOrderPriorityColumns(columns, orderPriorityList) {
    let orderArray = [];
    orderArray = columns.filter((item) => item.sort && item.hidden !== true)
      .map((item) => {
      return { name: item.name, orderIndex: 0 };
    });
    let indexCount = 0;
    let newOrderArray = [];
    orderPriorityList.forEach((orderPriorityItem) => {
      let item = orderArray.find((column) => column.name === orderPriorityItem.id);
      if (item) {
        item.orderIndex = indexCount;
        newOrderArray.push(item);
        indexCount++;
      }
    });
    if (newOrderArray.length > 0) {
      orderArray = newOrderArray;
    }
    return orderArray;
  }
  save() {
    var _a;
    let _newConfig;
    if (this.config) {
      _newConfig = this.config;
    }
    else {
      _newConfig = this.createConfigFromState(this.columns);
    }
    let _newColumnConfigList = [];
    let orderArray;
    if (((_a = this._orderPriorityList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      orderArray = this.reOrderPriorityColumns(this.columns, this._orderPriorityList);
    }
    this.columns.forEach((column) => {
      let _newColumnConfig = _newConfig.columns.find((_newColumnConfig) => column.name === _newColumnConfig.name);
      if (column.hidden === true && _newColumnConfig)
        return;
      if (!_newColumnConfig && column.hidden === false) {
        _newColumnConfig = { name: column.name, orderIndex: 0 };
      }
      if (_newColumnConfig) {
        if (column.sort) {
          _newColumnConfig.ascending = column.sort.toUpperCase() === ORDER_VALUES.asc.value ? true : false;
          if (orderArray) {
            adjustPriorityOrder(column, _newColumnConfig);
          }
          else {
            _newColumnConfig.orderIndex = column.sortIndex;
          }
        }
        else {
          delete _newColumnConfig.ascending;
          _newColumnConfig.orderIndex = 0;
        }
        _newColumnConfig.configVersion = SnkGridConfig.CURRENT_CONFIG_VERSION;
        _newColumnConfigList.push(_newColumnConfig);
      }
    });
    _newConfig.columns = _newColumnConfigList;
    this.saveGridConfigOnStorage(_newConfig);
    function adjustPriorityOrder(column, _newColumnConfig) {
      if (orderArray) {
        let orderItem = orderArray.find((item) => item.name === column.name);
        if (orderItem) {
          _newColumnConfig.orderIndex = orderItem.orderIndex;
        }
      }
    }
  }
  createConfigFromState(state) {
    let newConfig = { columns: [] };
    state.forEach((columnState) => {
      if (!columnState.hidden) {
        let newConfigColumn = { name: columnState.name };
        if (columnState.width) {
          newConfigColumn['width'] = columnState.width;
        }
        if (columnState.sort) {
          newConfigColumn['ascending'] = (columnState.sort.toUpperCase() === ORDER_VALUES.asc.value);
          newConfigColumn['orderIndex'] = columnState.sortIndex;
        }
        else {
          newConfigColumn['orderIndex'] = 0;
        }
        if (newConfigColumn) {
          newConfig.columns.push(newConfigColumn);
        }
      }
    });
    return newConfig;
  }
  closeConfig() {
    if (this._dataChanged) {
      let options = {
        canClose: false,
        labelCancel: this.getMessage('snkGridConfig.confirm.cancel'),
        labelConfirm: this.getMessage('snkGridConfig.confirm.save'),
        btnConfirmDanger: false,
      };
      ApplicationUtils.confirm(this.getMessage('snkGridConfig.confirm.alert'), this.getMessage('snkGridConfig.confirm.msgCancel'), null, DialogType.WARN, options)
        .then((response) => {
        if (!response) {
          this._dataChanged = false;
          this._orderPriorityList = [];
          this.configCancel.emit();
          this._componenteInternalKey = Date.now();
        }
        else {
          this.finish();
        }
      });
    }
    else {
      this.configCancel.emit();
    }
  }
  handleColumnListChange(evt) {
    var _a;
    if (evt.detail) {
      let visibleItems = (_a = evt.detail.find((group) => group.group === this.getMessage('snkGridConfig.group.visible'))) === null || _a === void 0 ? void 0 : _a.items;
      if (visibleItems) {
        this._dataChanged = true;
        this._orderListItems = visibleItems;
      }
    }
  }
  handleOrderListChange(evt) {
    if (evt.detail) {
      let orderPriorityList = evt.detail;
      if (orderPriorityList) {
        this._dataChanged = true;
        this._orderPriorityList = orderPriorityList;
      }
    }
  }
  componentWillRender() {
    var _a;
    if (((_a = this.columns) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      this.createColumnList();
    }
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfo(this._element);
  }
  handleRightListChange(rightList) {
    const visibleGroup = this._columListItems.find(group => group.group === this.getMessage('snkGridConfig.group.visible'));
    if (visibleGroup && visibleGroup.items != rightList) {
      visibleGroup.items = rightList;
      this._dataChanged = true;
    }
  }
  getListSlots() {
    return {
      RIGHT_LIST: {
        itemRightSlotBuilder: (item) => this.buildOrderListSlot(item),
      },
    };
  }
  renderResetConfigBtn() {
    if (!this.resourceID)
      return;
    return h("ez-button", { class: "padding-right--medium", label: this.getMessage('snkGridConfig.reset'), onClick: () => this.setDefaultConfig() });
  }
  async setDefaultConfig() {
    var _a;
    if (!this.resourceID)
      return;
    this._dataChanged = true;
    this._orderPriorityList = [];
    const config = await ConfigStorage.getDefaultGridConfig(this.resourceID);
    const defaultVisibleCols = (_a = config === null || config === void 0 ? void 0 : config.columns.map(col => col.name)) !== null && _a !== void 0 ? _a : [];
    const visibleGroup = this.buildVisibleGroup();
    const hiddenGroup = this.buildHiddenGroup();
    const visibleItemsMap = new Map();
    this.columns.forEach(column => {
      const item = this.buildListItemFromColumn(column);
      if (defaultVisibleCols.includes(column.name)) {
        visibleItemsMap.set(column.name, item);
      }
      else {
        hiddenGroup.items.push(item);
      }
    });
    visibleGroup.items = defaultVisibleCols
      .map(name => visibleItemsMap.get(name))
      .filter(item => item);
    this._columListItems = [visibleGroup, hiddenGroup];
    this._visibleList = visibleGroup.items;
    this._hiddenList = hiddenGroup.items;
    this.updateColumns();
    this.createOrderList();
  }
  buildListItemFromColumn(column) {
    var _a;
    return {
      label: column.label,
      selected: false,
      sort: (_a = column === null || column === void 0 ? void 0 : column.sort) !== null && _a !== void 0 ? _a : ORDER_VALUES.asc.value,
      id: column.name,
    };
  }
  render() {
    return (h(Host, null, h("div", { class: "grid-config__header" }, h("div", { class: "title-container" }, h("div", { class: "ez-margin-bottom--medium" }, h("label", { class: "title" }, this.getMessage('snkGridConfig.gridConfiguration')), h("label", { class: "subtitle" }, this.getMessage('snkGridConfig.columnVisibilityOrder'))), h("div", { class: "button-close" }, h("ez-button", { mode: "icon", iconName: "close", size: "medium", class: "ez-button--tertiary", onClick: () => this.closeConfig() })))), h("div", { class: 'grid-config__body' }, h("ez-collapsible-box", { id: 'group-select-columns', label: this.getMessage('snkGridConfig.columnsSelection'), "header-size": "medium", key: 'key_group-select-columns', value: this._collapsibleBoxListSelect, onEzChange: ({ detail }) => this._collapsibleBoxListOrder = !detail }, h("div", { class: "grid-config__main" }, h("ez-double-list", { leftList: this._hiddenList, leftTitle: this.getMessage('snkGridConfig.availableColumns'), rightList: this._visibleList, rightTitle: this.getMessage('snkGridConfig.selectedColumns'), onEzRightListChanged: ({ detail }) => this.handleRightListChange(detail), emptyMessage: {
        LEFT_LIST: this.getMessage('snkGridConfig.emptyMensage.left'),
        RIGHT_LIST: this.getMessage('snkGridConfig.emptyMensage.right'),
      }, entityLabel: 'coluna', entityLabelPlural: 'colunas' }))), h("ez-collapsible-box", { id: 'ID_group-order-columns', label: this.getMessage('snkGridConfig.dataOrdering'), "header-size": "medium", key: 'KEY_group-order-columns', value: this._collapsibleBoxListOrder, onEzChange: ({ detail }) => this._collapsibleBoxListSelect = !detail }, h("div", { class: "grid-config__main" }, h("ez-double-list", { rightList: this._orderListItems, rightTitle: this.getMessage('snkGridConfig.selectedColumns'), useOnlyRightList: true, slotsListBuilder: this.getListSlots(), onEzRightListChanged: (evt) => this.handleOrderListChange(evt), emptyMessage: {
        RIGHT_LIST: this.getMessage('snkGridConfig.emptyMensage.right'),
      }, entityLabel: 'coluna', entityLabelPlural: 'colunas' })))), h("div", { class: "grid-config__footer" }, this.renderResetConfigBtn(), h("ez-button", { class: "padding-right--medium", label: this.getMessage('snkGridConfig.cancel'), onClick: () => this.closeConfig() }), h("ez-button", { label: this.getMessage('snkGridConfig.complete'), class: "ez-button--primary", onClick: () => this.finish() }))));
  }
  static get assetsDirs() { return ["../assets"]; }
  get _element() { return this; }
  static get style() { return snkGridConfigCss; }
}, [2, "snk-grid-config", {
    "selectedIndex": [1026, "selected-index"],
    "columns": [1040],
    "config": [1040],
    "configName": [1, "config-name"],
    "resourceID": [1, "resource-i-d"],
    "_collapsibleBoxListOrder": [32],
    "_collapsibleBoxListSelect": [32]
  }]);
SnkGridConfig.CURRENT_CONFIG_VERSION = 1;
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-grid-config", "snk-select-box"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkGridConfig);
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkGridConfig as S, defineCustomElement as d };
