'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-17105557.js');
const core = require('@sankhyalabs/core');
const ParamType = require('./ParamType-90b440a0.js');

const SnkActionsForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.APPLY = 'OK';
    this.CANCEL = 'CANCEL';
    this.CLOSE = 'CLOSE';
    this.action = undefined;
    this.applyParameters = undefined;
    this.dataUnit = new core.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.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.ParamType.TEXT:
        return core.UserInterface.SHORTTEXT;
      case ParamType.ParamType.INTEGER:
        return core.UserInterface.INTEGERNUMBER;
      case ParamType.ParamType.DECIMAL:
        return core.UserInterface.DECIMALNUMBER;
      case ParamType.ParamType.DATE:
        return core.UserInterface.DATE;
      case ParamType.ParamType.DATETIME:
        return core.UserInterface.DATETIME;
      case ParamType.ParamType.BOOLEAN:
        return core.UserInterface.CHECKBOX;
      case ParamType.ParamType.ENTITY:
        return core.UserInterface.SEARCH;
      case ParamType.ParamType.OPTIONS:
        return core.UserInterface.OPTIONSELECTOR;
    }
  }
  getDataType(paramType) {
    switch (paramType) {
      case ParamType.ParamType.TEXT:
      case ParamType.ParamType.OPTIONS:
        return core.DataType.TEXT;
      case ParamType.ParamType.INTEGER:
      case ParamType.ParamType.DECIMAL:
        return core.DataType.NUMBER;
      case ParamType.ParamType.DATE:
      case ParamType.ParamType.DATETIME:
        return core.DataType.DATE;
      case ParamType.ParamType.BOOLEAN:
        return core.DataType.BOOLEAN;
      case ParamType.ParamType.ENTITY:
        return core.DataType.OBJECT;
    }
  }
  getProps(param) {
    switch (param.paramType) {
      case ParamType.ParamType.DECIMAL:
        return param.precision ? { precision: Number(param.precision) } : undefined;
      case ParamType.ParamType.ENTITY:
        return { ENTITYNAME: param.entityName };
      case ParamType.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 = core.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 (index.h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, ref: (ref) => this._ezPopup = ref }, index.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) }, index.h("div", { class: "ez-margin-vertical--medium" }, index.h("ez-form", { ref: (ref) => this._ezForm = ref, dataUnit: this.dataUnit })))));
  }
};

exports.snk_actions_form = SnkActionsForm;
