import {
    AfterContentInit,
    Component,
    ContentChildren,
    EventEmitter,
    Input,
    Output,
    QueryList
} from '@angular/core';
import {TabComponent} from '../tab/tab.component';

@Component({
  selector: 'app-tabs',
  templateUrl: './tabs.component.html',
  styleUrls: ['./tabs.component.scss']
})

export class TabsComponent implements AfterContentInit {

    @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;
    @Input() notifyOnChange = false;
    @Output() onChange: EventEmitter<number> = new EventEmitter<number>();

    constructor() { }

    /**
     * After content children are set
     */
    public ngAfterContentInit(): void {
        // get all active tabs
        const activeTabs = this.tabs.filter((tab) => tab.active);

        // if there is no active tab set, activate the first
        if (activeTabs.length === 0) {
            this.setSelectedTabIndex(0);
        }
    }

    /**
     * Eventlistener for tab change
     * @param {TabComponent} tab
     */
    public selectTab(tab: TabComponent): void {
        if (!tab.disabled) {
            if (this.notifyOnChange) {
                this.onChange.emit(tab.index);
            } else {
                this.setSelectedTabIndex(tab.index);
            }
        }
    }

    /**
     * Sets selected tab by given
     * @param {number} i
     */
    public setSelectedTabIndex(i: number): void {
        if (this.tabs != null) {
            const tabsArray: TabComponent[] = this.tabs.toArray();
            if (i < tabsArray.length) {
                // Deactivate all tabs
                tabsArray.forEach(tab => tab.active = false);
                // Activate the tab the user has clicked on.
                tabsArray[i].active = true;
            }
        }
    }

    /**
     * Disable tab at given index
     * @param {number} i
     */
    public disableTabIndex(i: number): void {
        this.toggleTabIndex(i, false);
    }

    /**
     * Enable tab at given index
     * @param {number} i
     */
    public enableTabIndex(i: number): void {
        this.toggleTabIndex(i, true);
    }

    /**
     * Sets selected tab disabled/enabled
     * @param {number} i
     * @param {boolean} enable
     */
    private toggleTabIndex(i: number, enable: boolean): void {
        if (this.tabs != null) {
            const tabsArray: TabComponent[] = this.tabs.toArray();
            if (i < tabsArray.length) {
                tabsArray[i].disabled = !enable;
            }
        }
    }

}
