import { h, r as registerInstance, c as createEvent, g as getElement, H as Host } from './index-baa5e267.js';
import { ObjectUtils, StringUtils, UserInterface, ElementIDUtils } from '@sankhyalabs/core';
import { C as CheckMode } from './CheckMode-bdb2ec19.js';
import { g as getI18n } from './index-41363fa6.js';

const buildSwitch = (field) => {
  return buildField(field.name, field.label, field.readOnly, field.contextName, true);
};
const buildCheckBox = (field) => {
  return buildField(field.name, field.label, field.readOnly, field.contextName, false);
};
function buildField(fieldName, fieldLabel, readOnly, contextName, switchMode) {
  return (h("div", { class: "ez-col ez-col--sd-12 ez-align--middle ez-padding-bottom--large" },
    h("ez-check", { enabled: !readOnly, label: fieldLabel, mode: switchMode ? CheckMode.SWITCH : CheckMode.REGULAR, "data-field-name": fieldName, "data-context-name": contextName, key: fieldName })));
}

const buildComboBox = ({ name, label, readOnly, required, props, contextName, canShowError }) => {
  const prop = props === null || props === void 0 ? void 0 : props.options;
  let options;
  if (typeof prop === "string") {
    const parsed = JSON.parse(prop);
    options = Object.keys(parsed).map(key => { return { value: key, label: parsed[key] }; });
  }
  else {
    options = prop;
  }
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-combo-box", { class: "ez-input__no-margin", enabled: !readOnly, suppressEmptyOption: required, label: label, "data-field-name": name, "data-context-name": contextName, key: name, options: options, canShowError: canShowError })));
};

const buildDate = ({ name, label, readOnly, canShowError }) => {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-date-input", { class: "ez-input__no-margin", enabled: !readOnly, label: label, "data-field-name": name, key: name, canShowError: canShowError })));
};
const buildTime = ({ name, label, readOnly, canShowError, props }) => {
  var _a;
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-time-input", { class: "ez-input__no-margin", enabled: !readOnly, label: label, "data-field-name": name, key: name, canShowError: canShowError, "show-seconds": (_a = props === null || props === void 0 ? void 0 : props.showSeconds) !== null && _a !== void 0 ? _a : false })));
};
const buildTimeSeconds = ({ name, label, readOnly, canShowError }) => {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-time-input", { class: "ez-input__no-margin", enabled: !readOnly, label: label, "data-field-name": name, key: name, canShowError: canShowError, showSeconds: true })));
};
const buildDateTime = ({ name, label, readOnly, contextName, canShowError }) => {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-date-time-input", { class: "ez-input__no-margin", enabled: !readOnly, label: label, "data-field-name": name, "data-context-name": contextName, key: name, canShowError: canShowError })));
};

const buildFile = ({ name, label, readOnly, contextName, props }) => {
  const uploadProps = ObjectUtils.removeEmptyValues({
    subTitle: props.subTitle,
    requestHeaders: Object.assign(Object.assign({}, (props.STORAGESTRATEGY && {
      STORAGESTRATEGY: props.STORAGESTRATEGY
    })), (props.INTERNAL_FILENAME && {
      INTERNAL_FILENAME: props.INTERNAL_FILENAME
    })),
  });
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-upload", Object.assign({ enabled: !readOnly, label: label, "data-field-name": name, "data-context-name": contextName, key: name }, uploadProps))));
};

const buildDecimal = ({ name, label, readOnly, props, contextName, canShowError }) => {
  var _a, _b;
  const precision = Number((_a = props === null || props === void 0 ? void 0 : props.precision) !== null && _a !== void 0 ? _a : 2);
  const prettyPrecision = Number((_b = props === null || props === void 0 ? void 0 : props.prettyPrecision) !== null && _b !== void 0 ? _b : precision);
  return buildNumeric(name, label, readOnly, precision, prettyPrecision, contextName, canShowError);
};
const buildInteger = ({ name, label, readOnly, contextName, canShowError }) => {
  return buildNumeric(name, label, readOnly, 0, 0, contextName, canShowError);
};
function buildNumeric(fieldName, fieldLabel, readOnly, precision, prettyPrecision, contextName, canShowError) {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-number-input", { class: "ez-input__no-margin", enabled: !readOnly, label: fieldLabel, precision: precision, prettyPrecision: prettyPrecision, "data-field-name": fieldName, "data-context-name": contextName, key: fieldName, canShowError: canShowError })));
}

const buildTextArea = ({ name, label, readOnly, contextName, rows, canShowError }) => {
  return (h("div", { class: "ez-col ez-col--sd-12", key: name },
    h("ez-text-area", { enabled: !readOnly, label: label, "data-field-name": name, "data-context-name": contextName, rows: rows, canShowError: canShowError })));
};

const buildTextInput = ({ name, label, readOnly, contextName, canShowError, props }) => {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-text-input", { class: "ez-input__no-margin", label: label, "data-field-name": name, "data-context-name": contextName, key: name, enabled: !readOnly, canShowError: canShowError, mask: props === null || props === void 0 ? void 0 : props.mask, "clean-value-mask": props === null || props === void 0 ? void 0 : props.cleanValueMask })));
};

const buildSearchPlus = ({ name, label, readOnly, contextName, canShowError, optionLoader, props }) => {
  const hasDescriptionField = !StringUtils.isEmpty(props === null || props === void 0 ? void 0 : props.DESCRIPTIONFIELD);
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-search-plus", { class: "ez-input__no-margin", enabled: !readOnly, label: label, "data-field-name": name, "data-context-name": contextName, key: name, canShowError: canShowError, optionLoader: optionLoader, hideDescriptionInput: !hasDescriptionField })));
};

const buildSearch = ({ name, label, readOnly, required, contextName, canShowError, optionLoader, props }) => {
  var _a;
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-search", { class: "ez-input__no-margin", enabled: !readOnly, suppressEmptyOption: required, label: label, "data-field-name": name, "data-context-name": contextName, key: name, canShowError: canShowError, optionLoader: optionLoader, ignoreLimitCharsToSearch: (_a = props === null || props === void 0 ? void 0 : props.ignoreLimitCharsToSearch) !== null && _a !== void 0 ? _a : false })));
};

const buildRichText = ({ name, label, readOnly, contextName, rows, canShowError }) => {
  return (h("div", { class: "ez-col ez-col--sd-12" },
    h("ez-rich-text", { key: name, enabled: !readOnly, label: label, "data-field-name": name, "data-context-name": contextName, rows: rows, canShowError: canShowError })));
};

const uiBuilders = new Map();
uiBuilders.set(UserInterface.CHECKBOX, buildCheckBox);
uiBuilders.set(UserInterface.SWITCH, buildSwitch);
uiBuilders.set(UserInterface.OPTIONSELECTOR, buildComboBox);
uiBuilders.set(UserInterface.DATE, buildDate);
uiBuilders.set(UserInterface.TIME, buildTime);
uiBuilders.set(UserInterface.ELAPSEDTIME, buildTimeSeconds);
uiBuilders.set(UserInterface.DATETIME, buildDateTime);
uiBuilders.set(UserInterface.FILE, buildFile);
uiBuilders.set(UserInterface.DECIMALNUMBER, buildDecimal);
uiBuilders.set(UserInterface.INTEGERNUMBER, buildInteger);
uiBuilders.set(UserInterface.SEARCH, buildSearch);
uiBuilders.set(UserInterface.SEARCHPLUS, buildSearchPlus);
uiBuilders.set(UserInterface.LONGTEXT, buildTextArea);
uiBuilders.set(UserInterface.HTML, buildRichText);
const fieldBuilder = (field) => {
  const i18n = getI18n();
  const builder = uiBuilders.get(field.userInterface) || buildTextInput;
  const label = field.required ? `${field.label}${i18n("app.requiredInfo")}` : field.label;
  const builtElement = builder(Object.assign(Object.assign({}, field), { label }));
  //@ts-ignore
  builtElement.$attrs$['data-form-item'] = field.name;
  return builtElement;
};

class FormItem {
  constructor(elem) {
    this.elem = elem;
  }
  addRightElement(el) {
    this.removeRightElement();
    el.classList.add('ez-padding-left--small');
    el.setAttribute('data-custom-item', 'true');
    this.elem.classList.add('ez-col--nowrap');
    this.elem.appendChild(el);
  }
  removeRightElement() {
    Array.from(this.elem.querySelectorAll('[data-custom-item="true"]')).forEach(item => item.remove());
  }
  get fieldName() {
    return this.elem.getAttribute('data-form-item');
  }
}
class FormItems {
  constructor(items, formId) {
    this.items = new Map();
    this.formId = formId;
    items.forEach(item => {
      const formItem = new FormItem(item);
      this.items.set(formItem.fieldName, formItem);
    });
  }
  getItem(name) {
    return this.items.get(name);
  }
  get formName() {
    return this.formId;
  }
}

const ezFormViewCss = ".sc-ez-form-view-h{display:flex;flex-wrap:wrap;width:100%;--ez-form-view__item--min-width:220px;--ez-form-view__item--max-width:440px;--ez-form-view__item--width:var(--space--small);--ez-form-view__item--padding:var(--space--small)}.form-view__content.sc-ez-form-view{display:grid;grid-template-columns:repeat(auto-fill, minmax(var(--ez-form-view__item--min-width), 1fr));gap:var(--ez-form-view__item--width);padding-inline:var(--ez-form-view__item--padding);width:100%}.form-view__content--single-column.sc-ez-form-view{grid-template-columns:repeat(1, minmax(var(--ez-form-view__item--min-width), var(--ez-form-view__item--max-width)))}.input-full_width.sc-ez-form-view{grid-column:1 / -1;width:100%}";

const EzFormView = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezContentReady = createEvent(this, "ezContentReady", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    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));
  }
  get _element() { return getElement(this); }
};
EzFormView.style = ezFormViewCss;

export { EzFormView as ez_form_view };
