import { Host, h } from '@stencil/core';
import { StringUtils } from '@sankhyalabs/core';
import { replaceHighlight, replaceQuotes } from '../../utils/searchFormatters';
export class SearchList {
  constructor() {
    this._startHighlightTag = "<span class='card-item__highlight'>";
    this._endHighlightTag = "</span>";
    this.MAX_HEIGHT = 350;
    this.HEADER_MENU_HEIGHT = 60;
    this.showLoading = undefined;
    this.visibleOptions = [];
    this.textEmptyList = undefined;
    this.canShowListOptions = undefined;
    this.value = undefined;
    this.showOptionValue = true;
    this.preSelection = undefined;
  }
  async nextOption() {
    const newPreSelection = this.preSelection === undefined ? 0 : Math.min(this.preSelection + 1, this.visibleOptions.length - 1);
    this.changePreSelection.emit(newPreSelection);
    this.scrollToOption(this.visibleOptions[newPreSelection]);
  }
  async previousOption() {
    const newPreSelection = this.preSelection === undefined ? 0 : Math.max(this.preSelection - 1, 0);
    this.changePreSelection.emit(newPreSelection);
    this.scrollToOption(this.visibleOptions[newPreSelection]);
  }
  selectOption(newOption) {
    const newOptionsReplaced = Object.assign(Object.assign({}, newOption), { value: replaceHighlight(newOption === null || newOption === void 0 ? void 0 : newOption.value), label: replaceHighlight(newOption === null || newOption === void 0 ? void 0 : newOption.label) });
    const newOptionsFormatted = Object.assign(Object.assign({}, newOptionsReplaced), { value: replaceQuotes(newOptionsReplaced === null || newOptionsReplaced === void 0 ? void 0 : newOptionsReplaced.value), label: replaceQuotes(newOptionsReplaced === null || newOptionsReplaced === void 0 ? void 0 : newOptionsReplaced.label) });
    this.changeValue.emit(newOptionsFormatted);
  }
  createOption(detail) {
    let { key, title } = detail;
    const startHighlight = new RegExp(this._startHighlightTag, 'g');
    const endHighlight = new RegExp(this._endHighlightTag, 'g');
    title = StringUtils.decodeHtmlEntities(title);
    const option = {
      value: key === null || key === void 0 ? void 0 : key.replace(startHighlight, '').replace(endHighlight, ''),
      label: title === null || title === void 0 ? void 0 : title.replace(startHighlight, '').replace(endHighlight, '')
    };
    this.selectOption(option);
  }
  scrollToOption(opt) {
    window.requestAnimationFrame(() => {
      const liElem = (opt === null || opt === void 0 ? void 0 : opt.value)
        ? this._optionsList.querySelector(`div#item_${opt.value.replace(/([ #;&,.+*~':"!^$[\]()=<>|/\\])/g, '\\$1')}`)
        : undefined;
      if (liElem) {
        liElem.scrollIntoView({ behavior: "smooth", block: "nearest" });
      }
    });
  }
  buildItem(opt, index) {
    opt.label = opt.label || opt.value;
    const card = {
      key: opt.value,
      title: opt.label,
      details: opt.details
    };
    return h("div", { style: { "height": "100%" }, class: index === this.preSelection ? "item preselected" : "item", id: `item_${opt.value}`, onMouseDown: () => this.createOption(card), onMouseOver: () => this.changePreSelection.emit(index) }, h("ez-card-item", { item: card, compacted: true, enableKey: this.showOptionValue }));
  }
  componentDidLoad() {
    if (this._optionsList) {
      this._optionsList.style.maxHeight = `${this.MAX_HEIGHT}px`;
    }
  }
  componentDidUpdate() {
    if (this._optionsList) {
      const rect = this._optionsList.getBoundingClientRect();
      const spaceBelow = window.innerHeight - rect.bottom;
      if (spaceBelow < 0) {
        this.adjustMaxHeight(rect);
      }
    }
  }
  adjustMaxHeight(rect) {
    if (this._optionsList) {
      const spaceAbove = rect.top - this.HEADER_MENU_HEIGHT;
      const maxHeight = this.MAX_HEIGHT;
      const height = Math.min(spaceAbove, maxHeight);
      this._optionsList.style.maxHeight = `${height}px`;
    }
  }
  cleanEmptyObjectArray(arr) {
    return arr.filter(item => {
      return Object.values(item).some(valor => valor !== undefined);
    });
  }
  render() {
    return (h(Host, null, h("ul", { class: "list-options", ref: elem => this._optionsList = elem }, !this.showLoading
      && this.cleanEmptyObjectArray(this.visibleOptions).length === 0
      && h("div", { class: "message" }, h("span", { class: "message__no-result" }, this.textEmptyList)), this.showLoading
      && h("div", { class: "message" }, h("div", { class: "message__loading" })), this.canShowListOptions && this.visibleOptions.map((opt, index) => this.buildItem(opt, index)))));
  }
  static get is() { return "search-list"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["search-list.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["search-list.css"]
    };
  }
  static get properties() {
    return {
      "showLoading": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "show-loading",
        "reflect": false
      },
      "visibleOptions": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Array<IOption>",
          "resolved": "IOption[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "IOption": {
              "location": "import",
              "path": "../../ez-search"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "textEmptyList": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "text-empty-list",
        "reflect": false
      },
      "canShowListOptions": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "can-show-list-options",
        "reflect": false
      },
      "value": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "IOption | string",
          "resolved": "IOption | string",
          "references": {
            "IOption": {
              "location": "import",
              "path": "../../ez-search"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "value",
        "reflect": false
      },
      "showOptionValue": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "show-option-value",
        "reflect": false,
        "defaultValue": "true"
      },
      "preSelection": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "pre-selection",
        "reflect": false
      }
    };
  }
  static get events() {
    return [{
        "method": "changeValue",
        "name": "changeValue",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IOption",
          "resolved": "IOption",
          "references": {
            "IOption": {
              "location": "import",
              "path": "../../ez-search"
            }
          }
        }
      }, {
        "method": "changePreSelection",
        "name": "changePreSelection",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "nextOption": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "previousOption": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
}
