import { Host, h } from '@stencil/core';
import { fieldBuilder } from './fieldbuilder/FieldBuilder';
import { ElementIDUtils, UserInterface } from '@sankhyalabs/core';
import { FormItems } from './structure';
export class EzFormView {
  constructor() {
    this._customEditors = new Map();
    this.fields = undefined;
    this.selectedRecord = undefined;
    this.singleColumn = false;
  }
  async showUp() {
    if (this.singleColumn)
      return;
    this._element.scrollIntoView({ behavior: "smooth", block: "start" });
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext });
    this._customEditors = newCustomEditors;
  }
  /**
   * Altera/adiciona uma propriedade nos metados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    const fields = this.fields.map(field => {
      if (field.name === fieldName && (value || value === 0)) {
        field.props = field.props || {};
        field.props[propName] = value;
      }
      return field;
    });
    this.fields = [...fields];
  }
  groupFields(fields) {
    const result = new Map();
    fields.forEach(item => {
      const groupLabel = item.group;
      if (groupLabel) {
        let groupFields = result.get(groupLabel);
        if (groupFields == undefined) {
          groupFields = [];
          result.set(groupLabel, groupFields);
        }
        groupFields.push(item);
      }
      else {
        result.set(item.name, item);
      }
    });
    return result;
  }
  componentDidRender() {
    this._formElements = Array.from(this._element.querySelectorAll("[data-field-name]"));
    this.ezContentReady.emit(this._formElements);
    const formItems = new FormItems(Array.from(this._element.querySelectorAll("[data-form-item]")));
    this.formItemsReady.emit(formItems);
  }
  isItemFullWidth(userInterface) {
    return [
      UserInterface.FILE,
      UserInterface.LONGTEXT,
      UserInterface.HTML,
    ].includes(userInterface);
  }
  buildFormItemElement(item, classItem = "") {
    var _a;
    if (this.isItemFullWidth(item.userInterface)) {
      classItem += " input-full_width";
    }
    if (this._customEditors.has(item.name)) {
      const value = (_a = this._formElements.map(el => ({ name: el.dataset.fieldName, value: el['value'] })).find(field => field.name === item.name)) === null || _a === void 0 ? void 0 : _a.value;
      const customEditor = this._customEditors.get(item.name).customEditor;
      return h("div", { class: classItem }, h("ez-custom-form-input", { "data-field-name": item.name, customEditor: customEditor, formViewField: item, builderFallback: fieldBuilder, value: value, selectedRecord: this.selectedRecord }));
    }
    return h("div", { class: classItem }, fieldBuilder(item));
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._element, 'ezFormView');
    if (this.fields == undefined) {
      return;
    }
    let nonArrayGrup = [];
    let formContent = Array.from(this.groupFields(this.fields).entries()).map(([label, value]) => {
      if (Array.isArray(value)) {
        return (h("ez-collapsible-box", { id: `group-${label}`, label: label, "header-size": "large", key: label }, h("div", { class: `form-view__content ${this.singleColumn && "form-view__content--single-column"}` }, value.map(fi => (this.buildFormItemElement(fi))))));
      }
      else {
        nonArrayGrup.push(value);
      }
    });
    // Filtra os elementos que não são arrays e os coloca dentro de uma única div
    let nonArrayElements = nonArrayGrup.map((value) => this.buildFormItemElement(value));
    let groupedNonArrayElements = h("div", { class: `form-view__content ${this.singleColumn && "form-view__content--single-column"}` }, nonArrayElements);
    return (h(Host, null, groupedNonArrayElements, formContent));
  }
  static get is() { return "ez-form-view"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-form-view.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-form-view.css"]
    };
  }
  static get properties() {
    return {
      "fields": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Array<IFormViewField>",
          "resolved": "IFormViewField[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "IFormViewField": {
              "location": "import",
              "path": "./interfaces/IFormViewField"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a lista de metadados usada para criar os campos de user interface."
        }
      },
      "selectedRecord": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Record",
          "resolved": "Record",
          "references": {
            "Record": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define os registros da linha selecionada."
        }
      },
      "singleColumn": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o formulario deve possuir apenas 1 coluna."
        },
        "attribute": "single-column",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "_customEditors": {}
    };
  }
  static get events() {
    return [{
        "method": "ezContentReady",
        "name": "ezContentReady",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Evento emitido quando o componente foi totalmente carregado na DOM."
        },
        "complexType": {
          "original": "Array<HTMLElement>",
          "resolved": "HTMLElement[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }, {
        "method": "formItemsReady",
        "name": "formItemsReady",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por notificar quando ocorrer a renderiza\u00E7\u00E3o de itens do formul\u00E1rio."
        },
        "complexType": {
          "original": "FormItems",
          "resolved": "FormItems",
          "references": {
            "FormItems": {
              "location": "import",
              "path": "./structure"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "showUp": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "addCustomEditor": {
        "complexType": {
          "signature": "(fieldName: string, customEditor: ICustomEditor, detailContext?: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomEditor": {
              "location": "import",
              "path": "../../utils/customEditor/interfaces/ICustomEditor"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um editor customizado para campos da grade e formul\u00E1rio.",
          "tags": []
        }
      },
      "setFieldProp": {
        "complexType": {
          "signature": "(fieldName: string, propName: string, value: any) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Altera/adiciona uma propriedade nos metados do campo.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
}
