import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from "@angular/core";

@Component({
    selector: 'combobox',
    templateUrl: './single.component.html',
    styleUrls: ['../core/core.component.css','./single.component.css'],
})
export class ComboboxSingleComponent implements OnInit {
    @Input() selectedItem = { value: null, text: '' };
    @Input() placeholder: string = 'Choose An Item ....';
    @Input() items: any[] = [];

    focusedIndex = 0;

    constructor(private element: ElementRef) { }
    ngOnInit(): void {}

    open() { 
        if(!this.element.nativeElement.classList.contains('open')) {
            this.element.nativeElement.classList.add('open');
            let items = this.getItems();
            items.filter((value,index) => { if(value.text == this.selectedItem.text) this.focusedIndex = index; return false; });
        }
    }
    close() { 
        if(this.element.nativeElement.classList.contains('open')) {
            this.element.nativeElement.classList.remove('open');
        }
    }
    set(item: any) {
        this.selectedItem.value = item.value;
        this.selectedItem.text = item.text;
        this.focus();
    }
    setAndClose(item: any) { this.set(item); this.close(); }
    fixFocusIndex() {

    }
    getItems(): any[] {
        if (!this.selectedItem.value) {
            return this.items.filter((value) => { return value.text.toLowerCase().indexOf(this.selectedItem.text.toLowerCase()) > -1; });
        }
        return this.items;
    }
    onkeyup(e: KeyboardEvent) {
        
        if (e.keyCode >= 37 && e.keyCode <= 40) {
            if (e.keyCode == 38) this.focusedIndex--;
            if (e.keyCode == 40) this.focusedIndex++;
            this.open();
            let ul = this.element.nativeElement.querySelector('ul.items');
            let li = ul.querySelector(`li:nth-child(${this.focusedIndex + 1})`);
            if(li) ul.scrollTop = li.offsetTop;
        }

        let item = this.items.filter((value,index) => { return value.text == this.selectedItem.text; });
        if (item.length == 1) this.set(item[0]);
        else this.selectedItem.value = null;

        let items = this.getItems();
        if (this.focusedIndex < 0) this.focusedIndex = 0;
        if (this.focusedIndex >= items.length) this.focusedIndex = items.length - 1;
        if (e.keyCode == 13) this.setAndClose(items[this.focusedIndex]);
    }
    focus() { this.element.nativeElement.querySelector('.search>input').focus(); }
    onblur() {
        if (this.element.nativeElement.querySelectorAll(':hover').length == 0) {
            this.close();
        }
    }
}