import { h } from '@stencil/core';
import { DataUnitInMemoryLoader, RECORD_DATE_FORMAT, } from '@sankhyalabs/core';
export class EzGridView {
  constructor() {
    this.inMemoryLoader = undefined;
    this.metadata = undefined;
    this.records = undefined;
    this.columnsConfig = undefined;
    this.pageSize = 150;
    this.recordDateFormat = RECORD_DATE_FORMAT.DD_MM_YYYY;
    this.multipleSelection = false;
    this.autoFocus = true;
    this.paginationCounterMode = 'auto';
    this.suppressCheckboxColumn = false;
    this.suppressFilterColumn = false;
    this.outlineMode = false;
    this.enableRowTableStriped = true;
    this.compact = false;
    this.useSearchColumn = true;
    this.suppressHorizontalScroll = false;
  }
  /**
   * Obtém o DataUnit da grade.
   */
  async getDataUnit() {
    if (!this.hasValidDependencies())
      return;
    this.ensureInMemoryLoaderExists();
    return this.inMemoryLoader.dataUnit;
  }
  /**
   * Recarrega os registros da grade.
   */
  async refresh() {
    await this.inMemoryLoader.dataUnit.loadData();
  }
  /**
   * Obtém as linhas selecionadas.
   */
  async getSelection() {
    var _a;
    return (_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.getSelection();
  }
  /**
   * Aplica um filtro rápido.
   */
  async quickFilter(term) {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.quickFilter(term));
  }
  /**
   * Localiza determinada coluna tornando-a visível.
   */
  async locateColumn(columnName) {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.locateColumn(columnName));
  }
  /**
   * Usa um argumento para filtrar as colunas por label
   */
  async filterColumns(search) {
    var _a;
    return (_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.filterColumns(search);
  }
  /**
   * Adiciona item de menu nas colunas.
   */
  async addColumnMenuItem(label, name, action, icon) {
    await this._gridRef.addColumnMenuItem(label, name, action, icon);
  }
  /**
   * Registra um formatador de valores para uma coluna da grid.
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.addCustomValueFormatter(columnName, customFormatter));
  }
  /**
   * Remove o formatador de valores de uma coluna da grid.
   */
  async removeCustomValueFormatter(columnName) {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.removeCustomValueFormatter(columnName));
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender, detailContext) {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.addGridCustomRender(fieldName, customRender, detailContext));
  }
  /**
   * Atribui o foco para a grade.
   */
  async setFocus() {
    var _a;
    await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.setFocus());
  }
  async handleMetadataChanged() {
    await this.configGrid();
  }
  async handleRecordsChanged() {
    await this.configGrid();
  }
  async handlePageSizeChanged() {
    await this.configGrid(true);
  }
  async handleRecordDateFormatChanged() {
    await this.configGrid(true);
  }
  async configGrid(forceRebuild = false) {
    if (!this.hasValidDependencies())
      return;
    this.ensureInMemoryLoaderExists(forceRebuild);
    this.updateDURecords();
    this.refreshFilterColumnDataSource();
  }
  updateDURecords() {
    requestAnimationFrame(() => {
      this.inMemoryLoader.records = this.records;
    });
  }
  refreshFilterColumnDataSource() {
    requestAnimationFrame(async () => {
      var _a;
      await ((_a = this._gridRef) === null || _a === void 0 ? void 0 : _a.refreshColumnFilterDataSource());
    });
  }
  hasValidDependencies() {
    return this.metadata && this.records;
  }
  buildGridConfig() {
    if (!this.columnsConfig)
      return;
    const columns = this.columnsConfig.map(this.parseColumnConfig.bind(this));
    return { columns };
  }
  parseColumnConfig(conf, index) {
    return Object.assign(Object.assign({}, conf), { orderIndex: index });
  }
  ensureInMemoryLoaderExists(forceRebuild = false) {
    if (forceRebuild) {
      this.clearInMemoryLoader();
    }
    this.buildInMemoryLoader();
  }
  buildInMemoryLoader() {
    requestAnimationFrame(() => {
      if (!this.inMemoryLoader) {
        this.inMemoryLoader = new DataUnitInMemoryLoader(this.metadata, this.records, this.buildInMemoryLoaderConfig());
      }
    });
  }
  clearInMemoryLoader() {
    this.inMemoryLoader = undefined;
  }
  buildInMemoryLoaderConfig() {
    const config = {
      pageSize: this.pageSize,
      recordDateFormat: this.recordDateFormat,
    };
    return config;
  }
  async componentDidLoad() {
    await this.configGrid();
  }
  render() {
    var _a;
    if (!((_a = this.inMemoryLoader) === null || _a === void 0 ? void 0 : _a.dataUnit) || !this.records)
      return;
    return (h("ez-grid", { ref: ref => this._gridRef = ref, canEdit: false, dataUnit: this.inMemoryLoader.dataUnit, config: this.buildGridConfig(), multipleSelection: this.multipleSelection, autoFocus: this.autoFocus, paginationCounterMode: this.paginationCounterMode, suppressCheckboxColumn: this.suppressCheckboxColumn, suppressFilterColumn: this.suppressFilterColumn, suppressHorizontalScroll: this.suppressHorizontalScroll, outlineMode: this.outlineMode, enableRowTableStriped: this.enableRowTableStriped, useSearchColumn: this.useSearchColumn, compact: this.compact, onEzPageChangedChanged: () => this.refreshFilterColumnDataSource() }, h("slot", { name: "leftButtons" }), h("slot", { name: "footer" })));
  }
  static get is() { return "ez-grid-view"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-grid-view.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-grid-view.css"]
    };
  }
  static get properties() {
    return {
      "metadata": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "UnitMetadata",
          "resolved": "UnitMetadata",
          "references": {
            "UnitMetadata": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Metadados que definem a estrutura da grade."
        }
      },
      "records": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Record[]",
          "resolved": "Record[]",
          "references": {
            "Record": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Registros a serem exibidos na grade."
        }
      },
      "columnsConfig": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "ColumnConfig[]",
          "resolved": "ColumnConfig[]",
          "references": {
            "ColumnConfig": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Configura\u00E7\u00E3o de exibi\u00E7\u00E3o da grade."
        }
      },
      "pageSize": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Quantidade de registros por p\u00E1gina."
        },
        "attribute": "page-size",
        "reflect": false,
        "defaultValue": "150"
      },
      "recordDateFormat": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "RECORD_DATE_FORMAT",
          "resolved": "RECORD_DATE_FORMAT.DD_MM_YYYY | RECORD_DATE_FORMAT.ISO",
          "references": {
            "RECORD_DATE_FORMAT": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Formato dos campos data dos registros."
        },
        "attribute": "record-date-format",
        "reflect": false,
        "defaultValue": "RECORD_DATE_FORMAT.DD_MM_YYYY"
      },
      "multipleSelection": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Habilita a sele\u00E7\u00E3o de v\u00E1rias linhas."
        },
        "attribute": "multiple-selection",
        "reflect": false,
        "defaultValue": "false"
      },
      "autoFocus": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Define se a grid ser\u00E1 focada ao ser carregada."
        },
        "attribute": "auto-focus",
        "reflect": false,
        "defaultValue": "true"
      },
      "paginationCounterMode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "'show' | 'hidden' | 'auto'",
          "resolved": "\"auto\" | \"hidden\" | \"show\"",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Define a forma como a pagina\u00E7\u00E3o ir\u00E1 se comportar."
        },
        "attribute": "pagination-counter-mode",
        "reflect": false,
        "defaultValue": "'auto'"
      },
      "suppressCheckboxColumn": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Informa se a coluna de chechbox deve ser suprimida"
        },
        "attribute": "suppress-checkbox-column",
        "reflect": false,
        "defaultValue": "false"
      },
      "suppressFilterColumn": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Informa se a grade deve suprimir o filtro de coluna."
        },
        "attribute": "suppress-filter-column",
        "reflect": false,
        "defaultValue": "false"
      },
      "outlineMode": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Altera visualmente as sombras e bordas do componente\nQuando false, aplica o padr\u00E3o de sombras ao componente (Utilizar quando for o elemento principal do layout)\nQuando true, aplica o padr\u00E3o de outline ao componente (Utilizar quando estiver contido em outro elemento como um painel ou pop-up)"
        },
        "attribute": "outline-mode",
        "reflect": false,
        "defaultValue": "false"
      },
      "enableRowTableStriped": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Ativa modo de linhas com cores alternadas."
        },
        "attribute": "enable-row-table-striped",
        "reflect": false,
        "defaultValue": "true"
      },
      "compact": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Define se a grade deve ser exibida em modo compacto"
        },
        "attribute": "compact",
        "reflect": false,
        "defaultValue": "false"
      },
      "useSearchColumn": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se a grade deve exibir um buscador de coluna com uso do Ctrl+F"
        },
        "attribute": "use-search-column",
        "reflect": false,
        "defaultValue": "true"
      },
      "suppressHorizontalScroll": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se a grade deve suprimir o scroll horizontal."
        },
        "attribute": "suppress-horizontal-scroll",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "inMemoryLoader": {}
    };
  }
  static get methods() {
    return {
      "getDataUnit": {
        "complexType": {
          "signature": "() => Promise<DataUnit>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            },
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          },
          "return": "Promise<DataUnit>"
        },
        "docs": {
          "text": "Obt\u00E9m o DataUnit da grade.",
          "tags": []
        }
      },
      "refresh": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Recarrega os registros da grade.",
          "tags": []
        }
      },
      "getSelection": {
        "complexType": {
          "signature": "() => Promise<Array<any>>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Array": {
              "location": "global"
            }
          },
          "return": "Promise<any[]>"
        },
        "docs": {
          "text": "Obt\u00E9m as linhas selecionadas.",
          "tags": []
        }
      },
      "quickFilter": {
        "complexType": {
          "signature": "(term: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Aplica um filtro r\u00E1pido.",
          "tags": []
        }
      },
      "locateColumn": {
        "complexType": {
          "signature": "(columnName: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Localiza determinada coluna tornando-a vis\u00EDvel.",
          "tags": []
        }
      },
      "filterColumns": {
        "complexType": {
          "signature": "(search: string) => Promise<Array<EzGridColumn>>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "EzGridColumn": {
              "location": "import",
              "path": "../ez-grid/controller/EzGridController"
            },
            "Array": {
              "location": "global"
            }
          },
          "return": "Promise<EzGridColumn[]>"
        },
        "docs": {
          "text": "Usa um argumento para filtrar as colunas por label",
          "tags": []
        }
      },
      "addColumnMenuItem": {
        "complexType": {
          "signature": "(label: string, name: string, action: Function, icon: HTMLElement | string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Function": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Adiciona item de menu nas colunas.",
          "tags": []
        }
      },
      "addCustomValueFormatter": {
        "complexType": {
          "signature": "(columnName: string, customFormatter: ICustomFormatter) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomFormatter": {
              "location": "import",
              "path": "../ez-grid/interfaces"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um formatador de valores para uma coluna da grid.",
          "tags": []
        }
      },
      "removeCustomValueFormatter": {
        "complexType": {
          "signature": "(columnName: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Remove o formatador de valores de uma coluna da grid.",
          "tags": []
        }
      },
      "addGridCustomRender": {
        "complexType": {
          "signature": "(fieldName: string, customRender: ICustomRender, detailContext?: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomRender": {
              "location": "import",
              "path": "../../utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um render customizado para colunas da grid.",
          "tags": []
        }
      },
      "setFocus": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Atribui o foco para a grade.",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "metadata",
        "methodName": "handleMetadataChanged"
      }, {
        "propName": "records",
        "methodName": "handleRecordsChanged"
      }, {
        "propName": "pageSize",
        "methodName": "handlePageSizeChanged"
      }, {
        "propName": "recordDateFormat",
        "methodName": "handleRecordDateFormatChanged"
      }];
  }
}
