import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { Select2Component, Select2OptionData } from 'ng2-select2';

@Component({
    selector: 'app-select-2',
    templateUrl: './select-2.component.html',
    styleUrls: ['./select-2.component.scss']
})
export class SelectTwoComponent {
    _items: Array<Select2OptionData>;
    _originalItems: Array<any> = [];
    _value: Select2OptionData;
    ignoreChange = false;

    @Input() fieldLabel: string;

    @Input() set data(items) {
        this._originalItems = items;
        this.ignoreChange = true;
        this._items = items.map(elem =>
            ({
                id: elem.ObjectID ? elem.ObjectID : elem.Value,
                text: elem[this.fieldLabel]
            }));

        setTimeout(() => {
            this.ignoreChange = false;
        });
    }

    @Input() set value(value) {
        this._value = value.ObjectID || value.Value;
    }

    @ViewChild('mySelect') mySelect: Select2Component;
    options: {};
    // tslint:disable-next-line:prefer-output-readonly
    @Output() valChange: EventEmitter<any> = new EventEmitter<any>();

    // tslint:disable-next-line:no-empty
    constructor() {
    }

    ngOnInit(): void {
        this.options = {minimumResultsForSearch: Infinity};
    }

    valueChanged(event): void {
        if (this.ignoreChange) {
            return;
        }
        try {
            const item = this._originalItems.find(items => items[this.fieldLabel] === event.data[0].text);
            if (item) {
                this.valChange.emit(item);
            }
            // tslint:disable-next-line:no-empty
        } catch (e) {
        }
    }
}
