import { r as registerInstance, h } from './index-e9c7ceaa.js';
import { DataUnit, UserInterface, DataType, ApplicationContext } from '@sankhyalabs/core';
import { P as ParamType } from './ParamType-d5152b06.js';

const SnkActionsForm = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.APPLY = 'OK';
    this.CANCEL = 'CANCEL';
    this.CLOSE = 'CLOSE';
    this.action = undefined;
    this.applyParameters = undefined;
    this.dataUnit = new DataUnit();
  }
  /**
   * Responsável por abrir a popup.
   */
  async openPopup() {
    this._ezPopup.opened = true;
  }
  ;
  exitPopup() {
    this._ezPopup.opened = false;
  }
  async handleApply() {
    try {
      await this._ezForm.validate();
      let row = this.dataUnit.getSelectedRecord();
      if (row) {
        this._params.forEach((param, index) => {
          if (row.hasOwnProperty(param.name)) {
            if (param.paramType == ParamType.ENTITY) {
              let searchValue = row[param.name];
              if (!searchValue) {
                param.value = null;
                return;
              }
              param.value = typeof searchValue === 'object' ? searchValue.value : searchValue;
              return;
            }
            this._params[index].value = row[param.name];
          }
          else {
            this._params[index].value = undefined;
          }
        });
        this.action.actionConfig.params.promptParam = this._params;
      }
      this.exitPopup();
      this.applyParameters(this.action);
    }
    catch (e) {
      // exceção ignorada, quando o validate() falha.
    }
  }
  searchLoader(evt, param) {
    const options = {
      entity: param.entityName,
      entityDescription: param.label
    };
    return this._application.executePreparedSearch(evt.mode, evt.argument, options);
  }
  ;
  getUserInterface(paramType) {
    switch (paramType) {
      case ParamType.TEXT:
        return UserInterface.SHORTTEXT;
      case ParamType.INTEGER:
        return UserInterface.INTEGERNUMBER;
      case ParamType.DECIMAL:
        return UserInterface.DECIMALNUMBER;
      case ParamType.DATE:
        return UserInterface.DATE;
      case ParamType.DATETIME:
        return UserInterface.DATETIME;
      case ParamType.BOOLEAN:
        return UserInterface.CHECKBOX;
      case ParamType.ENTITY:
        return UserInterface.SEARCH;
      case ParamType.OPTIONS:
        return UserInterface.OPTIONSELECTOR;
    }
  }
  getDataType(paramType) {
    switch (paramType) {
      case ParamType.TEXT:
      case ParamType.OPTIONS:
        return DataType.TEXT;
      case ParamType.INTEGER:
      case ParamType.DECIMAL:
        return DataType.NUMBER;
      case ParamType.DATE:
      case ParamType.DATETIME:
        return DataType.DATE;
      case ParamType.BOOLEAN:
        return DataType.BOOLEAN;
      case ParamType.ENTITY:
        return DataType.OBJECT;
    }
  }
  getProps(param) {
    switch (param.paramType) {
      case ParamType.DECIMAL:
        return param.precision ? { precision: Number(param.precision) } : undefined;
      case ParamType.ENTITY:
        return { ENTITYNAME: param.entityName };
      case ParamType.OPTIONS:
        return { options: this.prepareOptions(param.options) };
      default:
        return undefined;
    }
  }
  buildFields() {
    let fields = [];
    this._params.forEach((param, index) => {
      const hasName = !!param.name;
      let paramName = hasName ? param.name : `param_${index}`;
      fields.push({
        name: paramName,
        label: param.label,
        dataType: this.getDataType(param.paramType),
        userInterface: this.getUserInterface(param.paramType),
        readOnly: false,
        required: param.paramType == 'B' ? false : param.required === "true",
        properties: this.getProps(param)
      });
      this._params[index].name = paramName;
      this._params[index].isGeneratedName = !hasName;
    });
    const metadata = {
      name: 'params',
      label: 'params',
      fields: fields
    };
    this._metadata = metadata;
  }
  fillFields() {
    this._params.forEach((param) => {
      if (param.saveLast == 'true') {
        this.dataUnit.setFieldValue(param.name, param.value);
      }
    });
  }
  prepareOptions(options) {
    const optionsArray = options.split(";");
    let optionsList = optionsArray.map(function (opc, index) {
      let value;
      let label;
      if (opc.indexOf('=') > -1) {
        let opcArr = opc.split('=');
        value = opcArr[0];
        label = opcArr[1];
      }
      else {
        value = (index + 1).toString();
        label = opc;
      }
      return {
        value: value,
        label: label
      };
    });
    return optionsList;
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this._params = [...this.action.actionConfig.params.promptParam];
    this.dataUnit.metadataLoader = this.metadataLoader.bind(this);
    this.dataUnit.loadMetadata().then(() => {
      this.fillFields();
    });
    this.dataUnit.addRecord();
  }
  async metadataLoader() {
    return new Promise((resolve) => {
      this.buildFields();
      resolve(this._metadata);
    });
  }
  handleModalAction(evt) {
    switch (evt) {
      case this.APPLY:
        this.handleApply();
        break;
      case this.CANCEL:
      case this.CLOSE:
        this.exitPopup();
        break;
    }
  }
  render() {
    return (h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, ref: (ref) => this._ezPopup = ref }, h("ez-modal-container", { modalTitle: this._application.messagesBuilder.getMessage("snkActionsButton.form.fillParams", undefined), okButtonLabel: this._application.messagesBuilder.getMessage("snkActionsButton.buttons.apply", undefined), cancelButtonLabel: this._application.messagesBuilder.getMessage("snkActionsButton.buttons.cancel", undefined), onEzModalAction: (evt) => this.handleModalAction(evt.detail) }, h("div", { class: "ez-margin-vertical--medium" }, h("ez-form", { ref: (ref) => this._ezForm = ref, dataUnit: this.dataUnit })))));
  }
};

export { SnkActionsForm as snk_actions_form };
