import { Component, OnDestroy } from '@angular/core';
import { Store } from '@ngrx/store';
import {
    getUserState,
    UserState,
} from '@eui/core';
import { Observable, Subscription } from 'rxjs';
import { NavController } from "@ionic/angular";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
})
export class AppComponent implements OnDestroy {
    userInfos: UserState;
    // Observe state changes
    userState: Observable<UserState>;
    // an array to keep all subscriptions and easily unsubscribe
    subs: Subscription[] = [];

    public sidebarItems: MenuItem[] = [
        {
            label: 'Home', url: 'screen/home', icon: 'home-outline',
            iconColor: 'dark',
        },
        {
            isSection: true,
            label: 'MODULE 1',
        },
        { label: 'Module Page', url: 'screen/module1',
        icon: 'document-outline', iconColor: 'dark', },
        { label: 'Page 1', url: 'screen/module1/page1',
            icon: 'document-outline', iconColor: 'dark', },
        { label: 'Page 2', url: 'screen/module1/page2',
            icon: 'document-outline', iconColor: 'dark', },
        {
            isSection: true,
            label: 'MODULE 2',
        },
        { label: 'Module Page', url: 'screen/module2',
            icon: 'document-outline', iconColor: 'dark', },
        {
            label: 'About this app', url: 'screen/about',
            icon: 'phone-portrait-outline', iconColor: 'dark',
        },

    ];

    constructor(
        private store: Store<any>,
        private navCtrl:NavController,
    ) {
            this.userState = this.store.select(getUserState);
            this.subs.push(this.userState.subscribe((user: UserState) => {
                this.userInfos = { ...user };
            }));
    }

    ngOnDestroy() {
        this.subs.forEach((s: Subscription) => s.unsubscribe());
    }

    onItemClick(menuItem: MenuItem): void {
        if (menuItem && menuItem.url) {
            if (menuItem.url.indexOf('http') > -1) {
                window.open(menuItem.url, '_blank');
            } else {
                this.navCtrl.navigateRoot(menuItem.url).then();
            }
        }
    }

}

export interface MenuItem {
    icon?: string;
    iconColor?: string;
    label: string;
    url?: string;
    isSection?: boolean;
}
