import { h, Host } from '@stencil/core';
import { CustomEditorSource } from '../../../utils/customEditor/interfaces/ICustomEditor';
import { HTMLBuilder, ObjectUtils, StringUtils } from '@sankhyalabs/core';
export class EzCustomFormInput {
  constructor() {
    this.gui = undefined;
    this.customEditor = undefined;
    this.formViewField = undefined;
    this.value = undefined;
    this.detailContext = undefined;
    this.builderFallback = undefined;
    this.selectedRecord = undefined;
  }
  /**
   * Aplica foco no campo.
   */
  async setFocus() {
    var _a, _b;
    (_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["setFocus"]) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    var _a, _b;
    (_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["setBlur"]) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  /**
   * Retorna se o conteúdo é inválido.
   */
  async isInvalid() {
    var _a, _b;
    return ((_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["isInvalid"]) === null || _b === void 0 ? void 0 : _b.call(_a)) || false;
  }
  watchValue() {
    this.handleValue(this.gui);
  }
  watchCustomEditor() {
    this.getContent();
  }
  watchFormViewField(newValue, oldValue) {
    if (!ObjectUtils.equals(newValue, oldValue))
      this.getContent();
  }
  watchDetailContext() {
    this.getContent();
  }
  watchBuilderFallback() {
    this.getContent();
  }
  watchSelectedRecord(newValue, oldValue) {
    const newRecordId = newValue === null || newValue === void 0 ? void 0 : newValue['__record__id__'];
    const oldRecordId = oldValue === null || oldValue === void 0 ? void 0 : oldValue['__record__id__'];
    if (newRecordId !== oldRecordId) {
      this.getContent();
    }
  }
  getContent() {
    var _a, _b, _c, _d, _e;
    const fieldProps = new Map();
    for (const prop in this.formViewField.props) {
      fieldProps.set(prop, this.formViewField.props[prop]);
    }
    const params = {
      value: this.value,
      name: this.formViewField.name,
      currentEditor: this.builderFallback(this.formViewField),
      setValue: (value) => this.setValue(value),
      getValue: this.getValue,
      record: this.selectedRecord,
      editorMetadata: {
        label: this.formViewField.label,
        hidden: ((_a = this.formViewField.props) === null || _a === void 0 ? void 0 : _a.visible) === false,
        userInterface: this.formViewField.userInterface,
        options: (_b = this.formViewField.props) === null || _b === void 0 ? void 0 : _b.options,
        props: this.formViewField.props ? fieldProps : undefined,
        optionLoader: this.formViewField.optionLoader
      },
      source: CustomEditorSource.FORM,
      detailContext: this.detailContext
    };
    let gui = this.customEditor.getEditorElement(params);
    if (!gui) {
      gui = this.builderFallback(this.formViewField);
      this.handleValue(gui);
      this.gui = gui;
      return;
    }
    if (!(gui instanceof HTMLElement) && typeof gui !== 'string') {
      this.handleValue(gui);
      this.gui = gui;
      return;
    }
    if (typeof gui === 'string') {
      gui = HTMLBuilder.parseElement(gui);
    }
    const value = (_e = (_d = (_c = this.value) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : this.value) !== null && _e !== void 0 ? _e : '';
    gui.setAttribute('value', value);
    this.gui = h("div", { key: StringUtils.generateUUID(), ref: el => el && el.appendChild(gui) });
  }
  setValue(value) {
    this.value = value;
  }
  getValue() {
    return this.value;
  }
  handleValue(gui) {
    var _a;
    //@ts-ignore
    (_a = gui.$children$) === null || _a === void 0 ? void 0 : _a.forEach((child) => {
      child.$attrs$.value = this.value;
    });
  }
  componentWillLoad() {
    this.getContent();
  }
  render() {
    return (h(Host, null, this.gui));
  }
  static get is() { return "ez-custom-form-input"; }
  static get encapsulation() { return "scoped"; }
  static get properties() {
    return {
      "customEditor": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "ICustomEditor",
          "resolved": "ICustomEditor",
          "references": {
            "ICustomEditor": {
              "location": "import",
              "path": "../../../utils/customEditor/interfaces/ICustomEditor"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Inst\u00E2ncia do editor customizado."
        }
      },
      "formViewField": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IFormViewField",
          "resolved": "IFormViewField",
          "references": {
            "IFormViewField": {
              "location": "import",
              "path": "../interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Campo que o elemento customizado representa."
        }
      },
      "value": {
        "type": "any",
        "mutable": true,
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Valores dos campos do formul\u00E1rio."
        },
        "attribute": "value",
        "reflect": false
      },
      "detailContext": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define de qual contexto o editor est\u00E1 sendo acionado."
        },
        "attribute": "detail-context",
        "reflect": false
      },
      "builderFallback": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "(field: IFormViewField) => HTMLElement",
          "resolved": "(field: IFormViewField) => HTMLElement",
          "references": {
            "IFormViewField": {
              "location": "import",
              "path": "../interfaces"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Builder original do FormView que ser\u00E1 chamado caso o custom n\u00E3o retorne nenhum valor."
        }
      },
      "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."
        }
      }
    };
  }
  static get states() {
    return {
      "gui": {}
    };
  }
  static get methods() {
    return {
      "setFocus": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Aplica foco no campo.",
          "tags": []
        }
      },
      "setBlur": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Remove o foco do campo.",
          "tags": []
        }
      },
      "isInvalid": {
        "complexType": {
          "signature": "() => Promise<boolean>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Retorna se o conte\u00FAdo \u00E9 inv\u00E1lido.",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "value",
        "methodName": "watchValue"
      }, {
        "propName": "customEditor",
        "methodName": "watchCustomEditor"
      }, {
        "propName": "formViewField",
        "methodName": "watchFormViewField"
      }, {
        "propName": "detailContext",
        "methodName": "watchDetailContext"
      }, {
        "propName": "builderFallback",
        "methodName": "watchBuilderFallback"
      }, {
        "propName": "selectedRecord",
        "methodName": "watchSelectedRecord"
      }];
  }
}
