import { r as registerInstance, e as createEvent, i as forceUpdate, h, f as Host } from './index-e9c7ceaa.js';
import { UserInterface, StringUtils, ObjectUtils, ApplicationContext } from '@sankhyalabs/core';
import { b as VARS_BY_TYPE, D as DEFAULT_TYPE, c as TAGS_BY_TYPE } from './constants-7b422de0.js';
import { getConvertedValue } from '@sankhyalabs/core/dist/dataunit/metadata/DataType';
import { CheckMode } from '@sankhyalabs/ezui/dist/collection/utils';
import { f as getValidatedFieldValue, h as getEnabledByProperty, i as getValueByProperty, j as getIconName } from './FormConfigHelper-b9cf7758.js';

const fieldConfigCss = ".field-config-container.sc-field-config{font-family:'Roboto';color:#2b3a54;display:flex;flex-direction:column;gap:10px;width:330px;justify-content:space-between}.header.sc-field-config{display:flex;font-weight:500;font-size:16px}.actions.sc-field-config{display:flex;align-items:flex-end;justify-content:flex-end;gap:12px}";

const FieldConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.fieldConfigChanged = createEvent(this, "fieldConfigChanged", 7);
    this.fieldLabel = undefined;
    this.fieldLabelErrorMessage = undefined;
    this.fieldDefaultValue = undefined;
    this.fieldCleanOnCopy = undefined;
    this.fieldRequired = undefined;
    this.fieldReadOnly = undefined;
    this._defaultType = undefined;
    this.dataUnit = undefined;
    this.fieldConfig = undefined;
    this.fieldDescriptor = undefined;
    this.messagesBuilder = undefined;
  }
  observeFieldLabel() {
    if (this.validateFieldLabel) {
      this.fieldLabelErrorMessage = undefined;
    }
  }
  async show(_anchorElement) {
    this._popoupElement.opened = true;
    this.initializeValues();
    forceUpdate(this);
  }
  validateFieldLabel() {
    var _a;
    if ((_a = this.fieldLabel) === null || _a === void 0 ? void 0 : _a.trim())
      return true;
    this.applyErrorMessage();
    return false;
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  isAllowDefault() {
    var _a;
    const allowDefault = (_a = this.fieldDescriptor.properties) === null || _a === void 0 ? void 0 : _a.allowDefault;
    if (allowDefault == undefined) {
      return true;
    }
    return allowDefault === 'true';
  }
  enabledValueDefault() {
    var _a, _b, _c;
    const allowDefault = (_a = this.fieldDescriptor.properties) === null || _a === void 0 ? void 0 : _a.allowDefault;
    const hasVariableVar = (VARS_BY_TYPE.UserInterface.hasOwnProperty((_b = this.fieldDescriptor) === null || _b === void 0 ? void 0 : _b.userInterface)
      || ((_c = this.fieldDescriptor) === null || _c === void 0 ? void 0 : _c.userInterface) === UserInterface.SEARCH);
    return hasVariableVar && (allowDefault == undefined || allowDefault === 'true');
  }
  getDefaultType() {
    var _a, _b;
    return (_b = (_a = this.fieldDefaultValue) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : DEFAULT_TYPE.fixed;
  }
  emitFieldChanged() {
    this.fieldConfigChanged.emit(this.fieldConfig);
  }
  handleLabelChanged({ detail }) {
    this.fieldLabel = detail;
  }
  handleDefaultTypeChanged({ detail }) {
    const optionSelected = detail.value;
    if (optionSelected == undefined)
      return;
    this._defaultType = optionSelected;
    this.fieldDefaultValue = { type: this._defaultType };
  }
  handleDefaultValueChanged({ detail }) {
    this.fieldDefaultValue.value = detail === null || detail === void 0 ? void 0 : detail.value;
  }
  onChangeDefaultValue(fieldValue) {
    this.fieldDefaultValue.value = getValidatedFieldValue(fieldValue, this.dataUnit, this.fieldConfig.name);
  }
  handleClearDuplicateChanged({ detail }) {
    this.fieldCleanOnCopy = detail;
  }
  handleRequiredChanged({ detail }) {
    this.fieldRequired = detail;
  }
  handleReadOnlyChanged({ detail }) {
    this.fieldReadOnly = detail;
  }
  loadDefaultValue() {
    var _a;
    if ((_a = this.fieldConfig.defaultValue) === null || _a === void 0 ? void 0 : _a.type) {
      this._defaultType = this.fieldConfig.defaultValue.type;
      return;
    }
    this._defaultType = DEFAULT_TYPE.fixed;
    this.fieldConfig.defaultValue = { type: this._defaultType };
  }
  buildOptions() {
    let interfaceField = this.fieldDescriptor.userInterface;
    if (interfaceField === UserInterface.SEARCH) {
      interfaceField = UserInterface.INTEGERNUMBER;
    }
    return VARS_BY_TYPE.UserInterface[interfaceField];
  }
  renderDefaultValueEditor() {
    if (this._defaultType === DEFAULT_TYPE.variable) {
      return (h("ez-combo-box", { label: this.getMessage('snkConfigOptions.label.valueDefault'), enabled: this.isAllowDefault(), onEzChange: (e) => this.handleDefaultValueChanged(e), value: this.fieldDefaultValue.value, options: this.buildOptions() }));
    }
    return this.fieldDescriptor.userInterface &&
      this.buildFieldDefaultValueElement();
  }
  buildFieldDefaultValueElement() {
    var _a;
    const { userInterface, properties, dataType } = this.fieldDescriptor;
    const allowDefault = properties === null || properties === void 0 ? void 0 : properties.allowDefault;
    let value;
    let enabled = StringUtils.getBooleanValue(allowDefault, !this.fieldReadOnly);
    if (userInterface === UserInterface.FILE) {
      enabled = false;
    }
    if (enabled) {
      value = (_a = this.fieldDefaultValue) === null || _a === void 0 ? void 0 : _a.value;
      if (value != undefined) {
        value = getConvertedValue(dataType, value);
      }
    }
    const configField = {
      value,
      enabled,
      label: this.fieldConfig.label,
      name: this.fieldConfig.name,
      required: this.fieldRequired,
      userInterface,
    };
    switch (userInterface) {
      case UserInterface.SWITCH:
        return this.buildInputDefault(configField, undefined, CheckMode.SWITCH);
      case UserInterface.CHECKBOX:
        return this.buildInputDefault(configField, undefined, CheckMode.REGULAR);
      case UserInterface.OPTIONSELECTOR:
      case UserInterface.DECIMALNUMBER:
        return this.buildInputDefault(configField, properties);
      default:
        return this.buildInputDefault(configField);
    }
  }
  buildInputDefault({ value, enabled, label, name, required, userInterface }, properties = undefined, mode = undefined) {
    let options;
    let precision = 0;
    let prettyPrecision = 0;
    const TagName = userInterface == undefined || TAGS_BY_TYPE[userInterface] == undefined
      ? TAGS_BY_TYPE.DEFAULT
      : TAGS_BY_TYPE[userInterface];
    if (userInterface === UserInterface.OPTIONSELECTOR) {
      const prop = properties === null || properties === void 0 ? void 0 : properties.options;
      if (typeof prop === 'string') {
        const parsed = ObjectUtils.stringToObject(prop);
        options = Object.keys(parsed).map(key => {
          return { value: key, label: parsed[key] };
        });
      }
      else {
        options = prop;
      }
    }
    else if (userInterface === UserInterface.DECIMALNUMBER) {
      precision = Number((properties === null || properties === void 0 ? void 0 : properties.precision) || 2);
      prettyPrecision = Number((properties === null || properties === void 0 ? void 0 : properties.prettyPrecision) || precision);
    }
    return h(TagName, Object.assign({ value: value, enabled: enabled, label: label, "data-field-name": name, key: name, onEzChange: (evt) => this.onChangeDefaultValue(evt === null || evt === void 0 ? void 0 : evt.detail) }, (this.getConditionalAttributes(userInterface, required, options, precision, prettyPrecision, mode))));
  }
  getConditionalAttributes(userInterface, required, options, precision, prettyPrecision, mode) {
    const useSearchPlus = userInterface == UserInterface.SEARCHPLUS;
    switch (userInterface) {
      case UserInterface.SEARCH:
      case UserInterface.SEARCHPLUS:
        return {
          suppressEmptyOption: required,
          optionLoader: (searchArgument) => this.onSearchDefaultValue(searchArgument, { useSearchPlus }),
        };
      case UserInterface.OPTIONSELECTOR:
        return {
          suppressEmptyOption: required,
          options,
        };
      case UserInterface.CHECKBOX:
      case UserInterface.SWITCH:
        return {
          mode,
        };
      case UserInterface.INTEGERNUMBER:
      case UserInterface.DECIMALNUMBER:
        return {
          precision,
          prettyPrecision,
          onEzStartChange: (evt) => this.onChangeDefaultValue(evt === null || evt === void 0 ? void 0 : evt.detail),
        };
      case UserInterface.DATE:
      case UserInterface.DATETIME:
      case UserInterface.TIME:
        return {
          onEzStartChange: (evt) => this.onChangeDefaultValue(evt === null || evt === void 0 ? void 0 : evt.detail),
        };
      default:
        return {};
    }
  }
  onSearchDefaultValue(searchArgument, ctxOptions) {
    if (this._application && this.fieldConfig) {
      return this._application.executeSearch(searchArgument, this.fieldConfig.name, this.dataUnit, ctxOptions);
    }
  }
  initializeValues() {
    this.fieldLabel = this.fieldConfig.label;
    this.fieldDefaultValue = this.fieldConfig.defaultValue;
    this.fieldRequired = this.fieldConfig.required;
    this.fieldReadOnly = this.fieldConfig.readOnly;
    this.fieldCleanOnCopy = this.fieldConfig.cleanOnCopy;
  }
  handleApplyChanges() {
    if (!this.validateFieldLabel())
      return;
    this.fieldConfig.label = this.fieldLabel;
    this.fieldConfig.defaultValue = this.fieldDefaultValue;
    this.fieldConfig.required = this.fieldRequired;
    this.fieldConfig.readOnly = this.fieldReadOnly;
    this.fieldConfig.cleanOnCopy = this.fieldCleanOnCopy;
    this.emitFieldChanged();
    this._popoupElement.opened = false;
  }
  applyErrorMessage() {
    this.fieldLabelErrorMessage = `${this.getMessage('snkConfigOptions.validation.requiredField')} ${this.getMessage('snkConfigOptions.label.nameField')}`;
  }
  handleDiscardChanges() {
    this.initializeValues();
    this._popoupElement.opened = false;
  }
  componentWillLoad() {
    this.loadDefaultValue();
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
  }
  render() {
    return (h("ez-popup", { heightMode: 'auto', size: 'auto', "ez-title": this.getMessage('snkConfigOptions.fieldConfig.title'), onEzClosePopup: () => this.handleDiscardChanges(), ref: ref => this._popoupElement = ref }, h("div", { class: 'field-config-container' }, h("ez-text-input", { label: this.getMessage('snkConfigOptions.label.nameField'), value: this.fieldLabel, errorMessage: this.fieldLabelErrorMessage, hasInvalid: !!this.fieldLabelErrorMessage, onEzChange: (e) => this.handleLabelChanged(e) }), h("ez-combo-box", { label: this.getMessage('snkConfigOptions.label.typeValueDefault'), suppressEmptyOption: true, enabled: this.enabledValueDefault(), onEzChange: (e) => this.handleDefaultTypeChanged(e), value: this.getDefaultType() }, h("option", { value: DEFAULT_TYPE.fixed }, this.getMessage('snkConfigOptions.options.valueFixed')), h("option", { value: DEFAULT_TYPE.variable }, this.getMessage('snkConfigOptions.options.variable'))), this.renderDefaultValueEditor(), h("ez-check", { label: this.getMessage('snkConfigOptions.label.clearDuplicate'), value: this.fieldCleanOnCopy, onEzChange: (e) => this.handleClearDuplicateChanged(e) }), h("ez-check", { label: this.getMessage('snkConfigOptions.label.requiredField'), enabled: getEnabledByProperty('required', 'systemRequired', this.fieldDescriptor), value: getValueByProperty('required', this.fieldDescriptor, this.fieldRequired), onEzChange: (e) => this.handleRequiredChanged(e) }), h("ez-check", { label: this.getMessage('snkConfigOptions.label.protectedField'), enabled: getEnabledByProperty('readOnly', 'systemReadOnly', this.fieldDescriptor), value: getValueByProperty('readOnly', this.fieldDescriptor, this.fieldReadOnly), onEzChange: (e) => this.handleReadOnlyChanged(e) }), h("div", { class: 'actions' }, h("ez-button", { label: this.getMessage('snkConfigOptions.fieldConfig.buttons.cancel'), onClick: () => this.handleDiscardChanges() }), h("ez-button", { label: this.getMessage('snkConfigOptions.fieldConfig.buttons.confirm'), class: "ez-button--primary", onClick: () => this.handleApplyChanges() })))));
  }
  static get watchers() { return {
    "fieldLabel": ["observeFieldLabel"]
  }; }
};
FieldConfig.style = fieldConfigCss;

const fieldItemCss = ".sc-field-item-h{width:100%;display:flex;padding:12px 8px;border-radius:var(--border--radius-small, 4px);border:1px solid #dce0e8;cursor:grab;align-items:center;height:42px;max-height:42px;background:#FAFCFF}.full-width.sc-field-item-h{width:100%}ez-icon.sc-field-item{--ez-icon--color:#A2ABB9}.icons.sc-field-item{display:flex}.label.sc-field-item{display:flex;flex-grow:1;padding-left:8px;font-size:14px;align-items:center;gap:4px;height:22px}.label-text.sc-field-item{overflow:hidden;-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;height:auto;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;display:-webkit-box;-o-text-overflow:ellipsis;text-overflow:ellipsis;word-break:break-word}.required-mark.sc-field-item{color:#cf3105;background:#F7E0E5;width:12px;height:12px;border-radius:50%;display:flex;align-items:center;justify-content:center;padding-top:5px;font-size:16px;align-self:self-start}.actions.sc-field-item{display:flex;flex-direction:row;align-content:center;gap:4px}ez-button.sc-field-item{width:24px;align-items:center;justify-content:center;display:flex}.sc-field-item-h .hiddeble.sc-field-item{transition:0.2s ease-in-out;visibility:hidden;opacity:0}.sc-field-item-h:hover .hiddeble.sc-field-item{visibility:visible;opacity:1}";

const FieldItem = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.setFieldAsAvailable = createEvent(this, "setFieldAsAvailable", 7);
    this.addFieldToGuide = createEvent(this, "addFieldToGuide", 7);
    this.fieldDescriptor = undefined;
    this.fieldConfig = undefined;
    this.onLayoutConfig = false;
    this.dataUnit = undefined;
    this.messagesBuilder = undefined;
  }
  observeDataUnit() {
    this.loadFieldDescriptor();
  }
  isRequired() {
    var _a, _b;
    const fieldMD = this.dataUnit && this.dataUnit.getField((_a = this.fieldConfig) === null || _a === void 0 ? void 0 : _a.name);
    return (fieldMD === null || fieldMD === void 0 ? void 0 : fieldMD.required) === true || ((_b = this.fieldConfig) === null || _b === void 0 ? void 0 : _b.required) === true;
  }
  async showFieldConfig() {
    var _a;
    await ((_a = this._refFieldConfig) === null || _a === void 0 ? void 0 : _a.show(this._editIconRef));
  }
  renderFieldConfig() {
    if (this.onLayoutConfig && this.dataUnit && this.messagesBuilder) {
      return (h("field-config", { ref: (ref) => this._refFieldConfig = ref, fieldConfig: this.fieldConfig, dataUnit: this.dataUnit, fieldDescriptor: this.fieldDescriptor, messagesBuilder: this.messagesBuilder, onFieldConfigChanged: () => forceUpdate(this) }));
    }
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  renderActions() {
    if (this.onLayoutConfig) {
      return (h("div", { class: 'actions hiddeble' }, h("ez-button", { mode: "icon", class: "ez-button--tertiary", onClick: () => this.setFieldAsAvailable.emit(this.fieldConfig), size: "medium", iconName: 'minus', title: this.getMessage('snkFieldConfig.titleRemove') }), h("ez-button", { ref: ref => this._editIconRef = ref, mode: "icon", class: "ez-button--tertiary", onClick: this.showFieldConfig.bind(this), iconName: 'edit', size: "medium", title: this.getMessage('snkFieldConfig.titleEdit') })));
    }
    return (h("div", { class: 'actions hiddeble' }, h("ez-button", { mode: "icon", class: "ez-button--tertiary", onClick: () => this.addFieldToGuide.emit(this.fieldConfig), iconName: 'plus', size: "medium", title: this.getMessage('snkFieldConfig.titleAddToLayout') })));
  }
  loadFieldDescriptor() {
    if (this.dataUnit) {
      this.fieldDescriptor = this.dataUnit.getField(this.fieldConfig.name);
    }
  }
  renderRequiredMark() {
    if (this.isRequired())
      return h("span", { class: 'required-mark' }, "*");
  }
  componentWillLoad() {
    this.loadFieldDescriptor();
  }
  getFieldLabel() {
    var _a, _b;
    if ((_a = this.fieldConfig) === null || _a === void 0 ? void 0 : _a.label)
      return this.fieldConfig.label;
    return (_b = this.fieldDescriptor) === null || _b === void 0 ? void 0 : _b.label;
  }
  render() {
    var _a;
    return (h(Host, { class: !this.onLayoutConfig ? 'full-width' : "" }, h("div", { class: 'icons' }, h("ez-icon", { iconName: "drag-indicator" }), h("ez-icon", { iconName: getIconName((_a = this.fieldDescriptor) === null || _a === void 0 ? void 0 : _a.userInterface) })), h("span", { class: 'label' }, h("span", { class: 'label-text', title: this.getFieldLabel() }, this.getFieldLabel()), this.renderRequiredMark()), this.renderActions(), this.renderFieldConfig()));
  }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"]
  }; }
};
FieldItem.style = fieldItemCss;

export { FieldConfig as field_config, FieldItem as field_item };
