import { ApplicationContext } from '@sankhyalabs/core';
import { h } from '@stencil/core';
import { VIEW_MODE } from '../../lib/utils/constants';
import { AuthorizationConfig } from './AuthorizationConfig';
export class SnkConfigurator {
  constructor() {
    this._opened = false;
    this._permissions = undefined;
    this.showActionButtons = false;
    this.configName = undefined;
    this.resourceID = undefined;
    this.viewMode = VIEW_MODE.GRID;
    this.customContainerId = undefined;
    this.layoutFormConfig = true;
    this.messagesBuilder = undefined;
  }
  /**
   * Exibe a janela de configuração.
   */
  async open() {
    this._opened = true;
    this.configSelected.emit(this.getViewModeValue());
    this.modal.heightMode = 'full';
  }
  /**
   * Fecha a janela de configuração.
   */
  async close() {
    this.closeConfig();
  }
  closeConfig() {
    this._opened = false;
  }
  onViewModeChanged(evt) {
    const value = evt === null || evt === void 0 ? void 0 : evt.detail;
    this.viewMode = value;
    this.configSelected.emit(this.viewMode);
  }
  onClickOpenConfig() {
    this.openConfig.emit(this.viewMode);
  }
  isAllowed(configName) {
    if (AuthorizationConfig[configName]) {
      return this._permissions ? this._permissions.isSup || this._permissions[configName] : false;
    }
    return true;
  }
  enableModeConfig() {
    if (!this.isAllowed(AuthorizationConfig.CONFIG_GRID) || !this.isAllowed(AuthorizationConfig.CONFIG)) {
      return false;
    }
    return true;
  }
  getViewModeValue() {
    if (this._permissions != undefined) {
      if (!this.isAllowed(AuthorizationConfig.CONFIG_GRID)) {
        this.viewMode = VIEW_MODE.FORM;
      }
      else if (!this.isAllowed(AuthorizationConfig.CONFIG)) {
        this.viewMode = VIEW_MODE.GRID;
      }
    }
    return this.viewMode;
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-configurator.msg.ts"
   */
  getMessage(key) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, {});
  }
  handleSave() {
    if (this.layoutFormConfig) {
      this._snkLayoutFormConfig.save();
    }
    this.save.emit();
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    if (this._application) {
      this._application.getAllAccess(this.resourceID).then(access => (this._permissions = access));
    }
    else {
      this._permissions = {};
    }
  }
  componentDidRender() {
    if (!this.customContainerId)
      return;
    const container = document.querySelector(`#${this.customContainerId}`);
    const customElements = container === null || container === void 0 ? void 0 : container.querySelector('#SnkConfigContainerSlot');
    if (!customElements)
      return;
    const configuratorCustomElement = customElements.firstElementChild;
    if (!configuratorCustomElement)
      return;
    const insideCustomElementsContainer = this._element.querySelector("#slotContainer");
    insideCustomElementsContainer === null || insideCustomElementsContainer === void 0 ? void 0 : insideCustomElementsContainer.appendChild(configuratorCustomElement);
  }
  render() {
    return (h("ez-modal", { ref: (element) => (this.modal = element), opened: this._opened, "close-esc": false, "close-outside-click": false, "modal-size": "small", scrim: "light", onEzCloseModal: () => this.closeConfig() }, h("div", { class: "snk-configurator" }, h("div", { class: "snk-configurator__header" }, h("label", { class: "snk-configurator__title" }, this.getMessage('snkConfigurator.titleConfigurations')), h("div", { class: "snk-configurator__button-close" }, h("ez-button", { mode: "icon", iconName: "close", size: "medium", onClick: () => this.closeConfig() }))), h("div", { class: "snk-configurator__main" }, h("ez-collapsible-box", { boxBordered: true, label: this.getMessage('snkConfigurator.subTitleModeConfig'), headerSize: "medium", class: "snk-configurator__collapsable-box" }, h("ez-radio-button", { value: this.getViewModeValue().toString(), onEzChange: (evt) => this.onViewModeChanged(evt), enabled: this.enableModeConfig() }, h("ez-radio-button-option", { label: this.getMessage('snkConfigurator.labelGrid'), value: VIEW_MODE.GRID }), h("ez-radio-button-option", { label: this.getMessage('snkConfigurator.labelForm'), value: VIEW_MODE.FORM })), h("div", { class: "snk-configurator__collsable-box-action" }, h("ez-button", { label: this.viewMode === VIEW_MODE.GRID ? this.getMessage('snkConfigurator.labelConfigGrid') : this.getMessage('snkConfigurator.labelConfigForm'), class: "snk-configurator__button-config ez-button--secondary", onClick: () => this.onClickOpenConfig(), id: "openConfigurator" }))), this.layoutFormConfig && h("ez-collapsible-box", { boxBordered: true, value: true, label: this.getMessage('snkConfigurator.labelLayoutForm'), headerSize: "medium", class: "snk-configurator__collapsable-box  ez-margin-top--medium" }, h("div", { class: 'ez-flex ez-flex--column ez-size-width--full' }, h("snk-layout-form-config", { ref: (ref) => this._snkLayoutFormConfig = ref, messagesBuilder: this.messagesBuilder }))), h("div", { id: "slotContainer", class: "snk-configurator__outline" })), this.showActionButtons && (h("div", { class: "snk-configurator__action-buttons" }, h("ez-button", { label: this.getMessage('snkConfigurator.buttons.cancel'), onClick: () => this.cancel.emit() }), h("ez-button", { label: this.getMessage('snkConfigurator.buttons.save'), onClick: () => this.handleSave(), class: "ez-button--primary" }))))));
  }
  static get is() { return "snk-configurator"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-configurator.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-configurator.css"]
    };
  }
  static get properties() {
    return {
      "showActionButtons": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Usado para exibir os bot\u00F5es de a\u00E7\u00E3o"
        },
        "attribute": "show-action-buttons",
        "reflect": false,
        "defaultValue": "false"
      },
      "configName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Usado para guardar ou recuperar as configura\u00E7\u00F5es do formul\u00E1rio."
        },
        "attribute": "config-name",
        "reflect": false
      },
      "resourceID": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Identificador de recursos como configura\u00E7\u00F5es e acesso."
        },
        "attribute": "resource-i-d",
        "reflect": false
      },
      "viewMode": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "VIEW_MODE",
          "resolved": "VIEW_MODE.ATTACHMENT | VIEW_MODE.FORM | VIEW_MODE.GRID",
          "references": {
            "VIEW_MODE": {
              "location": "import",
              "path": "../../lib/utils/constants"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define qual modo de visualiza\u00E7\u00E3o est\u00E1 ativo."
        },
        "attribute": "view-mode",
        "reflect": false,
        "defaultValue": "VIEW_MODE.GRID"
      },
      "customContainerId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "ID do container que cont\u00E9m os elementos customizados do configurator."
        },
        "attribute": "custom-container-id",
        "reflect": false
      },
      "layoutFormConfig": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o LayoutFormConfig ser\u00E1 exibido no configurador."
        },
        "attribute": "layout-form-config",
        "reflect": false,
        "defaultValue": "true"
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por flexibilizar e padronizar o uso de mensagens nos blocos de constru\u00E7\u00E3o."
        }
      }
    };
  }
  static get states() {
    return {
      "_opened": {},
      "_permissions": {}
    };
  }
  static get events() {
    return [{
        "method": "configSelected",
        "name": "configSelected",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando seleciona o modo de visualiza\u00E7\u00E3o."
        },
        "complexType": {
          "original": "VIEW_MODE",
          "resolved": "VIEW_MODE.ATTACHMENT | VIEW_MODE.FORM | VIEW_MODE.GRID",
          "references": {
            "VIEW_MODE": {
              "location": "import",
              "path": "../../lib/utils/constants"
            }
          }
        }
      }, {
        "method": "openConfig",
        "name": "openConfig",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando clica para abrir a configura\u00E7\u00E3o."
        },
        "complexType": {
          "original": "VIEW_MODE",
          "resolved": "VIEW_MODE.ATTACHMENT | VIEW_MODE.FORM | VIEW_MODE.GRID",
          "references": {
            "VIEW_MODE": {
              "location": "import",
              "path": "../../lib/utils/constants"
            }
          }
        }
      }, {
        "method": "save",
        "name": "save",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando salva a configura\u00E7\u00E3o."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }, {
        "method": "cancel",
        "name": "cancel",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando cancela o salvamento da configura\u00E7\u00E3o."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "open": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Exibe a janela de configura\u00E7\u00E3o.",
          "tags": []
        }
      },
      "close": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Fecha a janela de configura\u00E7\u00E3o.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
}
