'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const __chunk_1 = require('./materials-f431cf7d.js');

/**
* Class that represent an autocomplete element
* composed by a textfield
* and a menu with selectable items for autocompletion
*/
class Autocomplete {
    constructor(hostRef) {
        __chunk_1.registerInstance(this, hostRef);
        /**
        * Apply low density on the element
        */
        this.dense = false;
        this.change = __chunk_1.createEvent(this, "change", 7);
    }
    componentDidLoad() {
        this.watchValue();
    }
    componentWillLoad() {
        this.watchValue();
    }
    watchValue() {
        if (this.value) {
            this.value.label = this.value.label ? this.value.label : this.value.value;
        }
        else {
            this.value = {
                value: null,
                label: null
            };
        }
    }
    selectSuggestion(key) {
        this.menuElement.close();
        if (this.suggestions) {
            const newValue = {
                value: key,
                label: this.suggestions.get(key)
            };
            this.value = Object.assign({}, newValue);
        }
        this.change.emit(this.value);
    }
    execAutocomplete(event) {
        this.value.label = event.target.value;
        this.autocomplete(event.target.value).then((suggests) => this.suggestions = suggests);
        this.menuElement.open();
    }
    emptyField() {
        if (!this.textElement.value) {
            this.value = null;
            this.change.emit(this.value);
        }
    }
    render() {
        return ([
            __chunk_1.h("materials-text-field", { ref: el => this.textElement = el, dense: this.dense, label: this.label, value: this.value.label, onInput: (ev) => this.execAutocomplete(ev), onChange: (ev) => {
                    ev.stopPropagation();
                    ev.preventDefault();
                    this.emptyField();
                } }),
            __chunk_1.h("materials-menu", { ref: el => this.menuElement = el }, this.suggestions ? Array.from(this.suggestions.keys()).map((key) => __chunk_1.h("materials-list-item", { onClick: () => this.selectSuggestion(key) }, this.suggestions.get(key))) : null)
        ]);
    }
    static get watchers() { return {
        "value": ["watchValue"]
    }; }
    static get style() { return ":host{display:block}"; }
}

exports.materials_autocomplete = Autocomplete;
