import { UserInterface } from '@sankhyalabs/core';
import { h } from '@stencil/core';
import { PRESENTATION_FROM_COL_PROP_NAME } from '../../../utils/constants';
import initI18n from '../../../utils/i18n';
const windowInstace = window;
const onSubmitFilter = new CustomEvent('onSubmitFilter', {
  detail: {
    showToast: true,
  },
});
export class FilterColumn {
  constructor() {
    this.opened = true;
    this.columnName = undefined;
    this.columnLabel = undefined;
    this.gridHeaderHidden = false;
    this.noHeaderTaskBar = false;
    this.dataSource = undefined;
    this.dataUnit = undefined;
    this.options = undefined;
    this.selectedItems = undefined;
    this.fieldDescriptor = undefined;
    this.useOptions = false;
    this.isTextSearch = false;
  }
  async hide() {
    await this.ezPopoverElement.hide();
    await this.clearConfigs();
  }
  /**
   * Abre o filtro de coluna.
   * @Params IFilterColumnConfigs informações para configurar o filtro
   */
  async show(configs) {
    var _a;
    if (this.canShow(configs)) {
      this.fieldDescriptor = (_a = configs.fieldDescriptor) !== null && _a !== void 0 ? _a : this.dataUnit.getField(configs.columnName);
      this.buildIsTextSearch();
      this.columnName = configs.columnName;
      this.columnLabel = configs.columnLabel;
      await this.setOptions(configs);
      await this.ezPopoverElement.showUnder(`filter-column-${configs.columnName}-${this.dataUnit.dataUnitId}`);
    }
  }
  buildIsTextSearch() {
    var _a, _b;
    const userInterface = (_b = (_a = this.fieldDescriptor) === null || _a === void 0 ? void 0 : _a.userInterface) !== null && _b !== void 0 ? _b : UserInterface.SHORTTEXT;
    this.isTextSearch = !(userInterface === UserInterface.DECIMALNUMBER || userInterface === UserInterface.INTEGERNUMBER);
  }
  async clearConfigs() {
    var _a;
    await ((_a = this.ezMultiSelectionList) === null || _a === void 0 ? void 0 : _a.clearFilteredOptions());
    this.options = null;
    this.columnName = null;
  }
  canShow(configs) {
    return !this.ezPopoverElement.opened || configs.columnName !== this.columnName;
  }
  submit() {
    this.applyFilterColumnOptions.emit({
      field: this.columnName,
      values: this.selectedItems,
    });
    windowInstace.dispatchEvent(onSubmitFilter);
    this.hide();
  }
  changeSelectedItems(items) {
    this.selectedItems = items;
  }
  hasToUseOptions() {
    return this.fieldDescriptor.userInterface === UserInterface.OPTIONSELECTOR
      || this.fieldDescriptor.userInterface === UserInterface.SWITCH
      || this.fieldDescriptor.userInterface === UserInterface.CHECKBOX;
  }
  isCheckBoxOrSwitch() {
    return this.fieldDescriptor.userInterface === UserInterface.SWITCH
      || this.fieldDescriptor.userInterface === UserInterface.CHECKBOX;
  }
  async setOptions(config) {
    var _a, _b, _c, _d;
    const selectedItems = config.filteredOptions;
    const validateFieldUserInterfaceOptionSelector = this.hasToUseOptions();
    if (validateFieldUserInterfaceOptionSelector) {
      this.useOptions = validateFieldUserInterfaceOptionSelector;
      this.options = validateFieldUserInterfaceOptionSelector ? this.buildOptions(selectedItems) : (selectedItems !== null && selectedItems !== void 0 ? selectedItems : null);
      return;
    }
    let colName = this.columnName;
    const staticOptionsConfig = { onlyLabel: false };
    if ((_b = (_a = config.fieldDescriptor) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b[PRESENTATION_FROM_COL_PROP_NAME]) {
      colName = (_d = (_c = config.fieldDescriptor) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d[PRESENTATION_FROM_COL_PROP_NAME];
      staticOptionsConfig.onlyLabel = true;
    }
    const options = await this.dataSource.getStaticOptions(colName, staticOptionsConfig);
    if (options != undefined) {
      const selected = new Set((selectedItems || []).filter(item => item.check).map(item => item.label));
      this.useOptions = true;
      this.options = selected.size === 0 ? options : options.map(option => (Object.assign(Object.assign({}, option), { check: selected.has(option.label) })));
      return;
    }
    this.useOptions = false;
    this.options = null;
  }
  buildOptions(selectedItems) {
    var _a, _b;
    if (selectedItems && selectedItems.length > 0) {
      return selectedItems;
    }
    if (this.isCheckBoxOrSwitch()) {
      return [
        { label: this.i18n("app.yes"), value: 'true', check: true },
        { label: this.i18n("app.no"), value: 'false', check: true },
      ];
    }
    const options = (_b = (_a = this.fieldDescriptor) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.options;
    if (Array.isArray(options)) {
      return options.map((option) => {
        return { label: option.value, value: option.value, check: true };
      });
    }
    const optionsObject = JSON.parse(options);
    const objectKeys = Object.keys(optionsObject);
    return objectKeys.map(key => {
      return { label: optionsObject[key], value: key, check: true };
    });
  }
  handleEzVisibilityChange(event) {
    if (event.detail === false) {
      this.clearConfigs();
    }
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  render() {
    return (h("ez-popover-plus", { ref: (element) => (this.ezPopoverElement = element), class: 'filter-column__popover', "overlay-type": 'none', autoClose: true, onEzVisibilityChange: this.handleEzVisibilityChange.bind(this) }, h("section", { class: 'filter-column' }, h("header", { class: 'filter-column__header' }, h("span", { class: 'ez-text ez-text--medium filter-column__header-title' }, this.i18n("ez-grid.filterColumnHeader", { columnLabel: this.columnLabel })), h("ez-button", { mode: 'icon', "icon-name": 'close', class: 'ez-button--tertiary', onClick: () => this.hide() })), h("ez-multi-selection-list", { id: 'filter-column-selection-list', columnName: this.columnName, dataSource: this.dataSource, options: this.options, useOptions: this.useOptions, ref: (element) => (this.ezMultiSelectionList = element), onChangeFilteredOptions: (event) => this.changeSelectedItems(event.detail), isTextSearch: this.isTextSearch, "data-element-id": this.columnName }), h("footer", { class: 'filter-column__footer' }, h("ez-button", { label: this.i18n("app.apply"), class: 'ez-button--primary', onClick: this.submit.bind(this) })))));
  }
  static get is() { return "filter-column"; }
  static get originalStyleUrls() {
    return {
      "$": ["filter-column.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["filter-column.css"]
    };
  }
  static get properties() {
    return {
      "opened": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "opened",
        "reflect": false,
        "defaultValue": "true"
      },
      "columnName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "column-name",
        "reflect": false
      },
      "columnLabel": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "column-label",
        "reflect": false
      },
      "gridHeaderHidden": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "grid-header-hidden",
        "reflect": false,
        "defaultValue": "false"
      },
      "noHeaderTaskBar": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "no-header-task-bar",
        "reflect": false,
        "defaultValue": "false"
      },
      "dataSource": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IMultiSelectionListDataSource",
          "resolved": "IMultiSelectionListDataSource",
          "references": {
            "IMultiSelectionListDataSource": {
              "location": "import",
              "path": "../../ez-multi-selection-list/interfaces/IMultiSelectionListDataSource"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "dataUnit": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "options": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IMultiSelectionOption[]",
          "resolved": "IMultiSelectionOption[]",
          "references": {
            "IMultiSelectionOption": {
              "location": "import",
              "path": "../../ez-multi-selection-list/interfaces/IMultiSelectionOption"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      }
    };
  }
  static get states() {
    return {
      "selectedItems": {},
      "fieldDescriptor": {},
      "useOptions": {},
      "isTextSearch": {}
    };
  }
  static get events() {
    return [{
        "method": "applyFilterColumnOptions",
        "name": "applyFilterColumnOptions",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IAppliedFilterColumnOptions",
          "resolved": "IAppliedFilterColumnOptions",
          "references": {
            "IAppliedFilterColumnOptions": {
              "location": "local"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "hide": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "show": {
        "complexType": {
          "signature": "(configs: IFilterColumnConfigs) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "IFilterColumnConfigs": {
              "location": "local"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Abre o filtro de coluna.",
          "tags": [{
              "name": "Params",
              "text": "IFilterColumnConfigs informa\u00E7\u00F5es para configurar o filtro"
            }]
        }
      }
    };
  }
}
