import { ElementIDUtils, FloatingManager } from '@sankhyalabs/core';
import { Host, h } from '@stencil/core';
import initI18n from '../../utils/i18n';
export class EzAlertList {
  constructor() {
    this._container = undefined;
    this.alerts = [];
    this.enableDragAndDrop = undefined;
    this.enableExpand = true;
    this.itemRightSlotBuilder = undefined;
    this.opened = true;
    this.expanded = false;
  }
  observeOpened() {
    if (this.opened) {
      this.manageOverlay();
    }
  }
  /**
   * Retorna o id do alerta a partir do título e do índice.
   */
  alertId(title, index) {
    const concatTitle = (title) => { var _a; return (_a = title === null || title === void 0 ? void 0 : title.split(' ').join('-')) !== null && _a !== void 0 ? _a : ""; };
    return `alert-${index}-${concatTitle(title)}`;
  }
  /**
   * Retorna o título do alerta a partir do id.
   */
  getAlertTitle(id) {
    var _a;
    return (_a = this.alerts.find((alert, index) => this.alertId(alert.title, index) === id)) === null || _a === void 0 ? void 0 : _a.title;
  }
  /**
   * Retorna o link para o titulo do alerta a partir do id.
   */
  getLinkActionClick(item) {
    var _a;
    const action = (_a = this.alerts.find((alert, index) => this.alertId(alert.title, index) === item.id)) === null || _a === void 0 ? void 0 : _a.onClickLink;
    if (action)
      return action;
    return () => { };
  }
  /**
    * Retorna o texto do título do alerta.
    */
  getTitleText(item) {
    var _a;
    const title = (_a = this.getAlertTitle(item.id)) !== null && _a !== void 0 ? _a : '';
    return `${title}${(title && item.label) ? ':' : ''}`;
  }
  /**
   * Gerencia a exibição do conteúdo expandido.
   */
  toggleExpandContainer() {
    if (!this.enableExpand) {
      return;
    }
    ;
    this.expanded = !this.expanded;
    this._container.classList.toggle('expanded', this.expanded);
    if (this.expanded) {
      this.updatePosition(this.getBoundingRight(), this.getBoundingBottom());
    }
    else {
      this.updatePosition(`10px`, `10px`);
    }
  }
  /**
   * Gerencia a exibição do overlay usando FloatingManager do Core.
   */
  manageOverlay() {
    if (this.opened && this._container) {
      this._overlayId = FloatingManager.float(this._container, this._overlayRef, this.getFloatOptions());
    }
    else {
      if (this._overlayId === undefined)
        return;
      FloatingManager.close(this._overlayId);
      this._overlayId = undefined;
    }
  }
  /**
   * Atualiza a posição da lista.
   */
  updatePosition(right, bottom) {
    if (this.opened) {
      FloatingManager.updateFloatPosition(this._container, this._overlayRef, Object.assign(Object.assign({}, this.getFloatOptions()), { right,
        bottom }));
    }
  }
  ;
  /**
   * Retorna valores padrões do componente
   */
  getFloatOptions() {
    return {
      autoClose: false,
      isFixed: true,
      bottom: '10px',
      right: '10px',
    };
  }
  ;
  /**
   * Retorna o valor para o alinhamento horizontal do componente.
   */
  getBoundingRight() {
    const docWidth = document.body.clientWidth;
    const boxWidth = this._container.getBoundingClientRect().width;
    return ((docWidth - boxWidth) / 2) + 'px';
  }
  /**
   * Retorna o valor para o alinhamento vertical do componente.
   */
  getBoundingBottom() {
    const docHeight = document.body.clientHeight;
    const boxHeight = this._container.getBoundingClientRect().height;
    return ((docHeight - boxHeight) / 2) + 'px';
  }
  componentDidLoad() {
    this.manageOverlay();
    if (this.opened && this._container) {
      this._container.focus();
    }
  }
  async componentWillLoad() {
    this.dataElementId = ElementIDUtils.addIDInfo(this._element, 'EzAlertList');
    this.i18n = await initI18n();
  }
  render() {
    return (h(Host, Object.assign({}, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: this.dataElementId }), this.opened ?
      (h("div", { ref: elem => (this._overlayRef = elem) }, h("div", { class: `alert-list__container ${this.expanded ? 'expanded' : ''}`, ref: elem => (this._container = elem) }, h("div", { class: "alert-list__content" }, h("div", { class: "alert-list__header" }, h("div", { class: "alert-list__title" }, `${this.i18n('app.alerts')} (${this.alerts.length})`), h("div", { class: "alert-list__header__buttons" }, this.enableExpand && (h("ez-button", { mode: "icon", size: "small", iconName: "expand", onClick: () => this.toggleExpandContainer(), "data-element-id": ElementIDUtils.getInternalIDInfo('expandButton'), title: this.expanded ? this.i18n('app.collapse') : this.i18n('app.expand') })), h("ez-button", { mode: "icon", size: "small", iconName: "close", "data-element-id": ElementIDUtils.getInternalIDInfo('closeButton'), onClick: () => {
          this.opened = false;
        }, title: this.i18n('app.close') }))), h("div", { class: "alert-list__expandable-content" }, h("ez-list", { itemSlotBuilder: this.itemRightSlotBuilder, hoverFeedback: true, itemLeftSlotBuilder: item => {
          return (h("a", { onClick: this.getLinkActionClick(item), style: {
              fontFamily: "var(--font-pattern, 'Roboto')",
              fontSize: 'var(--text--medium, 14px)',
              fontWeight: 'var(--text-weight--medium, 400)',
              color: 'var(--color--primary, #008561)',
              marginRight: '4px',
              cursor: 'pointer',
              display: 'flex',
              width: 'max-content',
              textDecoration: 'none'
            } }, this.getTitleText(item)));
        }, dataSource: this.alerts.map((alert, index) => {
          var _a;
          return {
            id: this.alertId(alert.title, index),
            label: (_a = alert.detail) !== null && _a !== void 0 ? _a : "",
          };
        }) })))))) : null));
  }
  static get is() { return "ez-alert-list"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-alert-list.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-alert-list.css"]
    };
  }
  static get properties() {
    return {
      "alerts": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "AlertItem[]",
          "resolved": "AlertItem[]",
          "references": {
            "AlertItem": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Lista de alertas que devem ser apresentados no componente."
        },
        "defaultValue": "[]"
      },
      "enableDragAndDrop": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o componente pode ser arrastado na tela."
        },
        "attribute": "enable-drag-and-drop",
        "reflect": true
      },
      "enableExpand": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o componente pode ser expandido."
        },
        "attribute": "enable-expand",
        "reflect": true,
        "defaultValue": "true"
      },
      "itemRightSlotBuilder": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "SlotBuilder",
          "resolved": "(item: ListItem, group?: ListGroup) => string | HTMLElement",
          "references": {
            "SlotBuilder": {
              "location": "import",
              "path": "../ez-list/ez-list"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define builder para elementos a direita do componente"
        }
      },
      "opened": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o componente est\u00E1 aberto."
        },
        "attribute": "opened",
        "reflect": true,
        "defaultValue": "true"
      },
      "expanded": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o componente est\u00E1 expandido."
        },
        "attribute": "expanded",
        "reflect": true,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "_container": {}
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "_container",
        "methodName": "observeOpened"
      }];
  }
}
