import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from "@angular/core";

@Component({
    selector: 'combobox-multiple',
    templateUrl: './multiple.component.html',
    styleUrls: ['../core/core.component.css','./multiple.component.css'],
})
export class ComboboxMultipleComponent implements OnInit {
    @Input() placeholder: string = 'Choose An Item ....';
    @Input() selectedItems = [];
    @Input() items: any[] = [];

    name: string;
    search: string = '';
    focusedIndex = 0;

    constructor(private element: ElementRef) { this.name = `combobox-${Math.round(Math.random() * 10000)}-`; }
    ngOnInit(): void {}

    open() { 
        if(!this.element.nativeElement.classList.contains('open')) {
            this.element.nativeElement.classList.add('open');
            let items = this.getItems();
        }
    }
    close() { 
        if(this.element.nativeElement.classList.contains('open')) {
            this.element.nativeElement.classList.remove('open');
        }
    }
    add(item: any) {
        item.checked = true;
        this.selectedItems.push(item);
        this.focus();
    }
    remove(item: any) {
        item.checked = false;
        let index = this.selectedItems.findIndex(value => { return value.value == item.value; });
        if(index > -1) this.selectedItems.splice(index,1);
        this.focus();
    }
    toggle(item: any) {
        let index = this.selectedItems.findIndex(value => { return value.value == item.value; });
        if(index > -1) {
            item.checked = false;
            this.selectedItems.splice(index,1);
        }
        else {
            item.checked = true;
            this.selectedItems.push(item);
        }
        this.focus();
    }
    getItems(): any[] {
        return this.items.filter((value) => { return value.text.toLowerCase().indexOf(this.search) > -1; });
    }
    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 items = this.getItems();
        if (this.focusedIndex < 0) this.focusedIndex = 0;
        if (this.focusedIndex >= items.length) this.focusedIndex = items.length - 1;
        if (e.keyCode == 13) {
            e.preventDefault();
            this.toggle(items[this.focusedIndex]);
        }
    }
    focus() { this.element.nativeElement.querySelector('.search>input').focus(); }
    onblur() {
        if (this.element.nativeElement.querySelectorAll(':hover').length == 0) {
            this.close();
        }
    }
}