import { Component, h, Prop, Event, State, Watch } from '@stencil/core';
export class UxplSelectInput {
  constructor() {
    /**
     * selector caption when no value eg: 'Select'
     */
    this.selectCaption = 'Select';
    /**
     * border
     */
    this.bordered = false;
    this.active = false;
    this.optionsInternal = [];
  }
  watchHandlerOpt(newValue, oldValue) {
    if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
      this.optionsInternal = this.options;
    }
  }
  watchHandlerVal(newValue, oldValue) {
    if (newValue !== oldValue) {
      if (this.options && this.options.length > 0) {
        let valOpt = this.options.find(opt => {
          return opt.value === newValue;
        });
        this.selected = [this.value];
        if (valOpt || newValue === undefined) {
          this.emitSelected();
        }
      }
    }
  }
  watchHandlerVals(newValues, oldValues) {
    if (this.mode === 'multi') {
      if (JSON.stringify(newValues) !== JSON.stringify(oldValues)) {
        this.selected = newValues;
        this.emitSelected();
      }
    }
  }
  toggleActive() {
    if (!this.disabled) {
      this.active = !this.active;
    }
  }
  get selectedValueString() {
    let returnStr = '';
    if (this.mode === 'multi') {
      const values = this.optionsInternal.filter(opt => {
        return this.values.includes(opt.value);
      });
      values.forEach(val => {
        returnStr = returnStr ? returnStr + ', ' + val.label : val.label;
      });
    }
    else {
      const selectedVal = this.optionsInternal && this.optionsInternal.find(opt => opt.value === this.value);
      if (!this.allowInput) {
        returnStr = selectedVal ? selectedVal.label : '- Invalid Selection -';
      }
      else {
        if (selectedVal && this.value === selectedVal.value) {
          return selectedVal.label;
        }
        if (this.textInput && (this.textInput.value !== undefined)) {
          if (selectedVal && selectedVal.label == this.textInput.value) {
            returnStr = selectedVal.label;
          }
          else {
            returnStr = this.textInput.value;
          }
        }
        else if (selectedVal) {
          returnStr = selectedVal.label;
        }
        else {
          returnStr = '';
        }
      }
    }
    return returnStr;
  }
  emitSelected() {
    if (this.mode === 'multi') {
      // this.uxplSelection.emit();
      const selOptions = this.calculateSelectedOptions();
      this.uxplSelection.emit(selOptions);
      this.uxplChanged.emit(selOptions);
    }
    else {
      if (this.optionsInternal) {
        const selOption = this.optionsInternal.find(opt => opt.value === this.value);
        this.uxplChanged.emit(selOption);
        this.uxplSelection.emit(selOption);
      }
    }
  }
  addEntry() {
    var _a;
    this.options = [...this.options, { label: (_a = this.textInput) === null || _a === void 0 ? void 0 : _a.value, value: this.textInput.value }];
    this.optionsInternal = this.options;
    this.setSelected(this.options[this.optionsInternal.length - 1]);
  }
  setSelected(option, manualChange) {
    if (this.mode === 'multi') {
      /*if (!this.values) {
        this.values = [];
      }*/
      this.optionsInternal = [...this.optionsInternal];
      if (this.values && this.values.includes(option.value)) {
        this.selected = this.values.filter(opt => { return opt !== option.value; });
        this.values = this.values.filter(opt => { return opt !== option.value; });
      }
      else {
        // this.values.push(option.value);
        if (this.values) {
          this.selected = [...this.values, option.value];
          this.values = [...this.values, option.value];
        }
        else {
          this.selected = [option.value];
          this.values = [option.value];
        }
      }
      // console.log(this.values);
      // this.uxplSelection.emit(this.calculateSelectedOptions());
      // this.uxplChanged.emit(this.calculateSelectedOptions());
    }
    else {
      if (!manualChange) {
        this.value = (this.value !== option.value || this.allowInput) ? option.value : undefined;
      }
      this.selected = [this.value];
      this.textInput.value = option.label;
      this.active = false;
      // console.log('firing event 2');
      //this.uxplSelection.emit(this.optionsInternal.find(opt => opt.value === this.value));
    }
  }
  calculateSelectedOptions() {
    return this.options.filter(opt => {
      return this.selected.includes(opt.value);
    });
  }
  componentWillLoad() {
    this.mode = this.multiple ? 'multi' : 'single';
    this.selected = this.values ? this.values : [this.value];
    // attach listener for click outside of pop-up
    document.addEventListener('click', (event) => {
      if (event.target === this.el) {
        // ignore event as inside control
      }
      else {
        this.active = false;
      }
    });
    if (this.options && this.options.length > 0) {
      this.optionsInternal = this.options;
    }
  }
  handleInput() {
    var _a;
    this.uxplInputChanged.emit((_a = this.textInput) === null || _a === void 0 ? void 0 : _a.value);
    this.active = true;
    if (this.textInput.value && this.textInput.value.length > 0) {
      // filter options
      this.optionsInternal = this.options.filter(opt => {
        return opt.label.toLowerCase().indexOf(this.textInput.value.toLowerCase()) !== -1;
      });
      if (this.optionsInternal.length < 1) {
        this.optionsInternal = [];
      }
    }
    else {
      this.optionsInternal = this.options;
    }
    let newOpt = this.optionsInternal.find(opt => opt.value === this.value);
    this.uxplChanged.emit(newOpt ? newOpt : { label: this.textInput.value, value: this.textInput.value });
  }
  handleKeyDown(e) {
    // capture tab
    let tabKey = 9;
    let enterKey = 13;
    if ((e.keyCode === tabKey || e.keyCode === enterKey) && this.optionsInternal.length === 1) {
      this.setSelected(this.optionsInternal[0]);
    }
  }
  clearSelection() {
    // unset everything
    this.selected = [];
    this.value = undefined;
    this.values = [];
    this.optionsInternal = this.options;
    if (!this.noCloseOnClear) {
      this.active = false;
    }
  }
  get isInList() {
    const val = this.optionsInternal.find((val) => {
      var _a, _b, _c, _d;
      return (val.label.toLowerCase() === ((_b = (_a = this.textInput) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.toLowerCase())) || (val.value.toLowerCase() === ((_d = (_c = this.textInput) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d.toLowerCase()));
    });
    return val !== undefined;
  }
  render() {
    var _a;
    return (h("host", null,
      h("div", { class: { "select-input-box": true, "bordered": this.bordered } },
        h("div", { class: {
            "pl-form-field": true,
            "pl-form-field--text-input": true,
            'has-error': this.valid === false,
            'disabled': this.disabled
          } },
          h("label", { class: { "pl-form-field__label": true, "active": this.active ? this.active : undefined }, part: this.required ? "required-label" : "optional-label", htmlFor: "{this.fieldId ? this.fieldId : 'pl-textbox'}" }, this.label),
          h("div", { class: { "input-section": true, 'active': this.active ? this.active : undefined }, onClick: () => this.toggleActive() },
            h("input", { ref: (el) => this.textInput = el, type: this.type, id: "{this.fieldId ? this.fieldId : 'pl-textbox'}", class: "pl-form-field__input", value: (this.values && this.values.length > 0) || this.value ? this.selectedValueString : undefined, placeholder: this.placeholder ? this.placeholder : this.selectCaption, disabled: this.mode != 'multi' && this.allowInput && !this.disabled ? false : true, required: this.required, onKeyUp: () => this.handleInput(), onKeyDown: (e) => this.handleKeyDown(e) }),
            h("div", { class: {
                'select-indicator': true,
                'active': this.active ? this.active : undefined
              } }))),
        h("div", { class: "pl-form-field__helper-text" }, this.hint),
        this.active ?
          h("ul", { class: {
              'uxpl-options-menu': true,
              "above": this.yPosition && this.yPosition.toLowerCase() === 'above',
              "below": this.yPosition && this.yPosition.toLowerCase() === 'below'
            }, style: {
              "max-height": this.maxHeight ? this.maxHeight : '150px'
            } },
            this.allowClear && this.optionsInternal && this.optionsInternal.length ?
              h("li", { class: "uxpl-options-menu-item", onClick: () => this.clearSelection() },
                h("div", null),
                h("a", { class: {
                    "uxpl-options-menu-item-link": true,
                    "single": this.mode === 'single' ? true : false
                  } }, "Clear selection"))
              : undefined,
            this.allowEdit && !this.multiple && ((_a = this.textInput) === null || _a === void 0 ? void 0 : _a.value) !== '' && !this.isInList ?
              h("li", { class: "uxpl-options-menu-item", onClick: () => this.addEntry() },
                h("div", null),
                h("a", { class: {
                    "uxpl-options-menu-item-link": true,
                    "single": this.mode === 'single' ? true : false
                  } },
                  "Select '",
                  this.textInput && this.textInput.value ? this.textInput.value : '',
                  "'"))
              : undefined,
            this.optionsInternal && this.optionsInternal.length > 0 ?
              this.optionsInternal.map((option) => h("li", { id: option.id, class: {
                  "uxpl-options-menu-item": true,
                  "disabled": option.disabled ? true : false
                }, onClick: () => option.disabled ? undefined : this.setSelected(option) },
                h("div", { class: {
                    'selection-indicator': true,
                    'selected': this.selected.includes(option.value) ? true : false
                  } }),
                h("a", { class: {
                    "uxpl-options-menu-item-link": true,
                    "single": this.mode === 'single' ? true : false
                  } }, option.label)))
              :
                h("li", { class: {
                    "uxpl-options-menu-item": true,
                    "disabled": true
                  } },
                  h("div", { class: {
                      'selection-indicator': true
                    } }),
                  !this.allowEdit ?
                    h("a", { class: {
                        "uxpl-options-menu-item-link": true,
                        "single": this.mode === 'single' ? true : false
                      } },
                      "No results found for '",
                      this.textInput && this.textInput.value ? this.textInput.value : '',
                      "'")
                    :
                      undefined))
          :
            undefined)));
  }
  static get is() { return "uxpl-select-input"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["uxpl-select-input.css"]
  }; }
  static get styleUrls() { return {
    "$": ["uxpl-select-input.css"]
  }; }
  static get assetsDirs() { return ["assets"]; }
  static get properties() { return {
    "fieldId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "fieldId"
      },
      "attribute": "field-id",
      "reflect": false
    },
    "allowClear": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "allow clear"
      },
      "attribute": "allow-clear",
      "reflect": false
    },
    "noCloseOnClear": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "dont close dropDown on clear"
      },
      "attribute": "no-close-on-clear",
      "reflect": false
    },
    "label": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "label"
      },
      "attribute": "label",
      "reflect": false
    },
    "type": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "type"
      },
      "attribute": "type",
      "reflect": false
    },
    "multiple": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Whether multiple selections allowed"
      },
      "attribute": "multiple",
      "reflect": false
    },
    "maxHeight": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Max height for pop up eg: 150px"
      },
      "attribute": "max-height",
      "reflect": false
    },
    "value": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "value (id from MenuOption[])"
      },
      "attribute": "value",
      "reflect": false
    },
    "values": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "string[]",
        "resolved": "string[]",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "array of ids from MenuOption[]"
      }
    },
    "options": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SelectOption[]",
        "resolved": "SelectOption[]",
        "references": {
          "SelectOption": {
            "location": "import",
            "path": "../../models/selectInputConfig"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "options"
      }
    },
    "yPosition": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "yPosition (above/below)"
      },
      "attribute": "y-position",
      "reflect": false
    },
    "hint": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "hint"
      },
      "attribute": "hint",
      "reflect": false
    },
    "selectCaption": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "selector caption when no value eg: 'Select'"
      },
      "attribute": "select-caption",
      "reflect": false,
      "defaultValue": "'Select'"
    },
    "placeholder": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "placeholder"
      },
      "attribute": "placeholder",
      "reflect": false
    },
    "disabled": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "disabled"
      },
      "attribute": "disabled",
      "reflect": false
    },
    "allowInput": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "allow input"
      },
      "attribute": "allow-input",
      "reflect": false
    },
    "allowEdit": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "allow edit"
      },
      "attribute": "allow-edit",
      "reflect": false
    },
    "required": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "required"
      },
      "attribute": "required",
      "reflect": false
    },
    "valid": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "required"
      },
      "attribute": "valid",
      "reflect": false
    },
    "bordered": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "border"
      },
      "attribute": "bordered",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "active": {},
    "optionsInternal": {}
  }; }
  static get events() { return [{
      "method": "uxplSelection",
      "name": "uxplSelection",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Value changed"
      },
      "complexType": {
        "original": "SelectOption[] | SelectOption",
        "resolved": "SelectOption | SelectOption[]",
        "references": {
          "SelectOption": {
            "location": "import",
            "path": "../../models/selectInputConfig"
          }
        }
      }
    }, {
      "method": "uxplChanged",
      "name": "uxplChanged",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Value changed"
      },
      "complexType": {
        "original": "SelectOption[] | SelectOption",
        "resolved": "SelectOption | SelectOption[]",
        "references": {
          "SelectOption": {
            "location": "import",
            "path": "../../models/selectInputConfig"
          }
        }
      }
    }, {
      "method": "uxplInputChanged",
      "name": "uxplInputChanged",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Input value"
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
  static get watchers() { return [{
      "propName": "options",
      "methodName": "watchHandlerOpt"
    }, {
      "propName": "value",
      "methodName": "watchHandlerVal"
    }, {
      "propName": "values",
      "methodName": "watchHandlerVals"
    }]; }
}
