import { Host, h } from '@stencil/core';
import { StringUtils } from '@sankhyalabs/core';
import initI18n from '../../../../utils/i18n';
export class EzSearchResultList {
  constructor() {
    this._startHighlightTag = "<span class='card-item__highlight'>";
    this._endHighlightTag = "</span>";
    this.showLoading = undefined;
    this.visibleOptions = [];
    this.value = undefined;
    this.showOptionValue = true;
    this._preSelection = undefined;
  }
  observerVisivleOptions(newValue) {
    if (newValue.length) {
      this.preSelectItemByIndex(0);
    }
  }
  async nextOption() {
    const newPreSelection = this._preSelection === undefined ? 0 : Math.min(this._preSelection + 1, this.visibleOptions.length - 1);
    this.preSelectItemByIndex(newPreSelection);
  }
  async previousOption() {
    const newPreSelection = this._preSelection === undefined ? 0 : Math.max(this._preSelection - 1, 0);
    this.preSelectItemByIndex(newPreSelection);
  }
  preSelectItemByIndex(newIndex) {
    this._preSelection = newIndex;
    const option = this.visibleOptions[newIndex];
    this.scrollToOption(option);
  }
  selectOption(newOption) {
    const newOptionsReplaced = Object.assign(Object.assign({}, newOption), { value: newOption === null || newOption === void 0 ? void 0 : newOption.value, label: newOption === null || newOption === void 0 ? void 0 : newOption.label });
    const newOptionsFormatted = Object.assign(Object.assign({}, newOptionsReplaced), { value: this.removeHighLight(newOptionsReplaced === null || newOptionsReplaced === void 0 ? void 0 : newOptionsReplaced.value), label: this.removeHighLight(newOptionsReplaced === null || newOptionsReplaced === void 0 ? void 0 : newOptionsReplaced.label) });
    this.changeValue.emit(newOptionsFormatted);
  }
  removeHighLight(text) {
    if (!text || typeof text !== 'string') {
      return text;
    }
    const startHighlight = new RegExp(this._startHighlightTag, 'g');
    const endHighlight = new RegExp(this._endHighlightTag, 'g');
    return text.replace(startHighlight, '').replace(endHighlight, '');
  }
  createAndSelectOption(detail) {
    let { key, title } = detail;
    key = String(key !== null && key !== void 0 ? key : "");
    title = StringUtils.decodeHtmlEntities(title);
    const option = {
      value: this.removeHighLight(key),
      label: this.removeHighLight(title)
    };
    this.selectOption(option);
  }
  scrollToOption(opt) {
    if (!(opt === null || opt === void 0 ? void 0 : opt.value) || !this._optionsList)
      return;
    window.requestAnimationFrame(() => {
      var _a;
      const currentValue = String((_a = opt === null || opt === void 0 ? void 0 : opt.value) !== null && _a !== void 0 ? _a : "");
      const liElem = currentValue
        ? this._optionsList.querySelector(`div#item_${currentValue.replace(/([ #;&,.+*~':"!^$[\]()=<>|/\\])/g, '\\$1')}`)
        : undefined;
      if (liElem) {
        liElem.scrollIntoView({ behavior: "smooth", block: "nearest" });
      }
    });
  }
  buildItem(opt, index) {
    var _a;
    opt.label = opt.label || opt.value;
    const card = {
      key: String((_a = opt.presentationValue) !== null && _a !== void 0 ? _a : ""),
      title: opt.presentationLabel,
      details: opt.details
    };
    return h("div", { style: { "height": "100%" }, class: index === this._preSelection ? "item preselected" : "item", id: `item_${opt.value}`, onMouseDown: () => this.createAndSelectOption(card), onMouseOver: () => { this._preSelection = index; } }, h("ez-card-item", { item: card, compacted: true, enableKey: this.showOptionValue }));
  }
  async selectCurrentItem() {
    this.selectOption(this.visibleOptions[this._preSelection]);
  }
  async cancelSelection() {
    this.cancelPreselection();
  }
  cancelPreselection() {
    this._preSelection = undefined;
  }
  canShowListOptions() {
    return !this.showLoading && this.visibleOptions.length > 0;
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  render() {
    return (h(Host, null, h("ul", { class: "list-options", ref: elem => this._optionsList = elem }, !this.showLoading
      && this.visibleOptions.length === 0
      && h("div", { class: "message" }, h("span", { class: "message__no-result" }, this.i18n("ez-search-plus.emptyList"))), this.showLoading && (h("div", { class: "loading__container" }, h("ez-skeleton", { count: 4, height: '20px' }))), this.canShowListOptions() && this.visibleOptions.map((opt, index) => this.buildItem(opt, index)))));
  }
  static get is() { return "ez-search-result-list"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-search-result-list.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-search-result-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-plus"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "value": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "IOption | string",
          "resolved": "IOption | string",
          "references": {
            "IOption": {
              "location": "import",
              "path": "../../ez-search-plus"
            }
          }
        },
        "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"
      }
    };
  }
  static get states() {
    return {
      "_preSelection": {}
    };
  }
  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-plus"
            }
          }
        }
      }];
  }
  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": []
        }
      },
      "selectCurrentItem": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "cancelSelection": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "visibleOptions",
        "methodName": "observerVisivleOptions"
      }];
  }
}
