import { h, forceUpdate, } from '@stencil/core';
import { DialogType } from "./DialogType";
import { ElementIDUtils, FloatingManager, KeyboardManager } from "@sankhyalabs/core";
import FocusResolver from '../../utils/FocusResolver';
import initI18n from '../../utils/i18n';
class Message {
  constructor(title, message, dialogType, confirm, icon, labelCancel, labelConfirm, btnConfirmDanger, callBack, beforeClose) {
    this.title = title;
    this.message = message;
    this.dialogType = dialogType;
    this.confirm = confirm;
    this.icon = icon;
    this.labelCancel = labelCancel;
    this.labelConfirm = labelConfirm;
    this.btnConfirmDanger = btnConfirmDanger;
    this.callBack = callBack;
    this.beforeClose = beforeClose;
  }
}
export class EzDialog {
  constructor() {
    this.PRIMARY_BUTTON_ID = "EZ_DIALOG_PRIMARY_BUTTON";
    this.btnConfirmDanger = false;
    this._messageQueue = [];
    this._canFocusOnPrimaryBtn = false;
    this.confirm = false;
    this.dialogType = undefined;
    this.message = undefined;
    this.opened = false;
    this.personalizedIconPath = undefined;
    this.ezTitle = undefined;
    this.beforeClose = undefined;
  }
  observeConfig(newValue, oldValue) {
    this.manageOverflow();
    //Eh preciso verificar se gouve de fato mudança do estado opened de FALSE para TRUE
    if (newValue && !oldValue) {
      this._canFocusOnPrimaryBtn = true;
    }
  }
  manageOverflow() {
    if (this.opened) {
      window.document.body.style.overflow = "hidden";
    }
    else {
      window.document.body.style.overflow = "";
    }
  }
  manageOverlay() {
    if (this.opened) {
      this._overlayId = FloatingManager.subscribeOverlayControl(this._overlayRef);
    }
    else {
      FloatingManager.unsubscribeOverlayControl(this._overlayRef || this._overlayId);
    }
  }
  handleButtonClick(selectedOption) {
    if (this._currentMessage.beforeClose && this._currentMessage.beforeClose(selectedOption) === false) {
      return;
    }
    this.opened = this._messageQueue.length > 0;
    if (this._currentMessage.callBack) {
      this._currentMessage.callBack(selectedOption);
    }
    selectedOption ? this.ezAccept.emit(selectedOption) : this.ezCancel.emit(selectedOption);
    this._currentMessage = this._messageQueue.shift();
    forceUpdate(this);
  }
  /**
   * Exibe o ez-dialog.
   */
  async show(title, message, dialogType, confirm, icon, labelCancel, labelConfirm, btnConfirmDanger, beforeClose) {
    this.opened = true;
    return new Promise(resolve => {
      this._messageQueue.push(new Message(title, message, dialogType, confirm, icon, labelCancel, labelConfirm, btnConfirmDanger, resolve, beforeClose));
    });
  }
  isCritical(dialogType) {
    return dialogType === DialogType.CRITICAL;
  }
  getIconElement(message) {
    if (message.dialogType === DialogType.DEFAULT) {
      return;
    }
    const iconClass = this.getIconClass(message.dialogType);
    return (h("div", { class: `changeable__icon__container ${iconClass}` }, h("ez-icon", { class: "changeable__icon", size: "small", iconName: this.getIconName(message) })));
  }
  getIconClass(dialogType) {
    if (this.isCritical(dialogType)) {
      return "title-icon--critical";
    }
    else if (dialogType === DialogType.SUCCESS) {
      return "title-icon--success";
    }
    else if (dialogType === DialogType.WARN) {
      return "title-icon--warn";
    }
    return "";
  }
  getIconName(message) {
    if (message.icon) {
      return message.icon;
    }
    else if (this.isCritical(message.dialogType)) {
      return "alert-circle-inverted";
    }
    else if (message.dialogType === DialogType.WARN) {
      return "warning-outline";
    }
    else if (message.dialogType === DialogType.SUCCESS) {
      return "check";
    }
  }
  getTypeIndicatorElement(message) {
    if (message.dialogType === DialogType.DEFAULT) {
      return;
    }
    return h("div", { class: this.getClassIconIndicator(message.dialogType) });
  }
  getClassIconIndicator(dialogType) {
    if (this.isCritical(dialogType)) {
      return "dialog__critical--indicator";
    }
    else if (dialogType == DialogType.SUCCESS) {
      return "dialog__success--indicator";
    }
    else if (dialogType == DialogType.WARN) {
      return "dialog__warning--indicator";
    }
    return "";
  }
  getClassContainer(message) {
    const type = message.dialogType || DialogType.DEFAULT;
    return type === DialogType.DEFAULT ? "dialog__container dialog__container--default" : "dialog__container";
  }
  getClassTitleLabel(message) {
    return this.getIconElement(message) == undefined ? "title title__label title__label--no-icon" : "title title__label";
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentWillRender() {
    if (!this._currentMessage) {
      if (this._messageQueue.length > 0) {
        this._currentMessage = this._messageQueue.pop();
      }
      else {
        if (this.opened) {
          this._currentMessage = new Message(this.ezTitle, this.message, this.dialogType, this.confirm, this.personalizedIconPath, this.i18n("app.no"), this.i18n("app.yes"), this.btnConfirmDanger, null, this.beforeClose);
        }
      }
    }
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfo(this._element);
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element })
      .bind("Enter", () => this.handleButtonClick(true), { description: this.i18n("ez-dialog.confirmButton"), element: this._element })
      .bind("Escape", () => this.handleButtonClick(false), { description: this.i18n("ez-dialog.closeButton"), element: this._element })
      .bind("Esc", () => this.handleButtonClick(false), { description: this.i18n("ez-dialog.closeButton"), element: this._element });
  }
  componentDidRender() {
    this.manageOverlay();
    this.focusOnDialog();
    this.handleFocusOnPrimaryButton();
  }
  focusOnDialog() {
    const dialog = this._element.shadowRoot.querySelector('.overlay .dialog');
    if (dialog instanceof HTMLDivElement) {
      dialog.style.outline = 'none';
      this._lastActiveElement = document.activeElement;
      dialog.focus();
    }
  }
  handleFocusOnPrimaryButton() {
    if (this._canFocusOnPrimaryBtn) {
      this.focusOnPrimaryButton();
      this._canFocusOnPrimaryBtn = false;
    }
  }
  focusOnPrimaryButton() {
    const btnConfirm = this._element.shadowRoot.querySelector(`#${this.PRIMARY_BUTTON_ID}`);
    const buttonElement = btnConfirm === null || btnConfirm === void 0 ? void 0 : btnConfirm.shadowRoot.querySelector('button');
    requestAnimationFrame(() => {
      buttonElement === null || buttonElement === void 0 ? void 0 : buttonElement.focus();
    });
  }
  disconnectedCallback() {
    var _a;
    FocusResolver.resolveFocus(this._lastActiveElement);
    this._lastActiveElement = undefined;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  render() {
    if (this.opened && this._currentMessage) {
      return (h("div", { class: "overlay", ref: ref => this._overlayRef = ref }, h("div", { tabindex: "-1", class: "dialog" }, this.getTypeIndicatorElement(this._currentMessage), h("div", { class: this.getClassContainer(this._currentMessage) }, h("div", { class: "title__container" }, h("div", { class: "title__box" }, this.getIconElement(this._currentMessage), h("div", { class: this.getClassTitleLabel(this._currentMessage), innerHTML: this._currentMessage.title, "data-element-id": ElementIDUtils.getInternalIDInfo("title") })), h("button", { class: "btn-close", onClick: () => this.handleButtonClick(false), "data-element-id": ElementIDUtils.getInternalIDInfo("buttonClose") })), h("div", { class: "message", innerHTML: this._currentMessage.message, "data-element-id": ElementIDUtils.getInternalIDInfo("message") }), this._currentMessage.confirm &&
        h("div", { class: "button-yes-no__container" }, h("ez-button", { class: "button__cancel", "data-element-id": ElementIDUtils.getInternalIDInfo("cancel"), label: this._currentMessage.labelCancel, onClick: () => this.handleButtonClick(false) }), h("ez-button", { id: this.PRIMARY_BUTTON_ID, class: !this._currentMessage.btnConfirmDanger ? "button__confirm" : "button__confirm--danger", "data-element-id": ElementIDUtils.getInternalIDInfo("confirm"), label: this._currentMessage.labelConfirm, onClick: () => this.handleButtonClick(true) })), !this._currentMessage.confirm &&
        h("div", { class: "button__confirm--container" }, h("ez-button", { id: this.PRIMARY_BUTTON_ID, label: 'Ok', "data-element-id": ElementIDUtils.getInternalIDInfo("ok"), class: "button__confirm", onClick: () => this.handleButtonClick(true) }))))));
    }
    return null;
  }
  static get is() { return "ez-dialog"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-dialog.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-dialog.css"]
    };
  }
  static get properties() {
    return {
      "confirm": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o ez-dialog ser\u00E1 utilizado no modo de confirma\u00E7\u00E3o."
        },
        "attribute": "confirm",
        "reflect": false,
        "defaultValue": "false"
      },
      "dialogType": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "DialogType",
          "resolved": "DialogType.CRITICAL | DialogType.DEFAULT | DialogType.SUCCESS | DialogType.WARN",
          "references": {
            "DialogType": {
              "location": "import",
              "path": "./DialogType"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define apar\u00EAncia do ez-dialog."
        },
        "attribute": "dialog-type",
        "reflect": false
      },
      "message": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a menssagem exibida no ez-dialog."
        },
        "attribute": "message",
        "reflect": false
      },
      "opened": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o ez-dialog est\u00E1 aberto."
        },
        "attribute": "opened",
        "reflect": true,
        "defaultValue": "false"
      },
      "personalizedIconPath": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o \u00EDcone a ser exibido."
        },
        "attribute": "personalized-icon-path",
        "reflect": false
      },
      "ezTitle": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Texto a ser apresentado como t\u00EDtulo do campo."
        },
        "attribute": "ez-title",
        "reflect": false
      },
      "beforeClose": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "Function",
          "resolved": "Function",
          "references": {
            "Function": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define fun\u00E7\u00E3o a ser executada antes de fechar o modal"
        }
      }
    };
  }
  static get events() {
    return [{
        "method": "ezCancel",
        "name": "ezCancel",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao cancelar o ez-dialog."
        },
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        }
      }, {
        "method": "ezAccept",
        "name": "ezAccept",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao confirmar o ez-dialog."
        },
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "show": {
        "complexType": {
          "signature": "(title: string, message: string, dialogType: DialogType, confirm: boolean, icon: string, labelCancel: string, labelConfirm: string, btnConfirmDanger: boolean, beforeClose: Function) => Promise<boolean>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "DialogType": {
              "location": "import",
              "path": "./DialogType"
            },
            "Function": {
              "location": "global"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Exibe o ez-dialog.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "opened",
        "methodName": "observeConfig"
      }];
  }
}
