import { OnInit } from '@angular/core';
import { MenuItem, SelectItem } from 'primeng/api';
import { AuthService } from 'ekangularbase/src/auth/auth.service';
import { OperatingCentreService, OperatingCentreClass } from 'ekangularbase/src/service/object/OperatingCentre.service';
import { AppConfig } from 'ekangularbase/src/AppConfig/AppConfig';
import { Router, NavigationEnd } from '@angular/router';
import { UserService } from 'ekangularbase/src/service/object/user.service';


export class HeaderBase implements OnInit {

    items: MenuItem[];
    allOcList: OperatingCentreClass[] = [];
    oclist: SelectItem[] = [];
    selectedoc: SelectItem;
    hideMenuText = '<<';
    pushRightClass = 'push-right';
    username = '';

    constructor(
        public authService: AuthService,
        public operatingCentreService: OperatingCentreService,
        public router: Router,
        public userService: UserService,
    ) {}

    ngOnInit(): void {
        this.router.events.subscribe(val => {
            if (
                val instanceof NavigationEnd &&
                window.innerWidth <= 992 &&
                this.isToggled()
            ) {
                this.toggleSidebar();
            }
        });

        this.initMenu();
        this.ngOnLocalInit();
    }

    ngOnLocalInit() {}

    initMenu() {
        this.authService.loadingcompleted.subscribe(s => {
            // alert('start ngam ngam');
            // this.updatenotificationbar();

            this.username = this.authService.getUserName();

            this.operatingCentreService.Get().subscribe(res => {
                if (res != null) {
                    this.allOcList = res;
                    // console.log("123");
                    // console.log(this.allOcList);
                    this.oclist = [];
                    let codes = this.authService.getOcCodes();
                    // Added by Rama - Start
                    if (typeof codes === 'string') {
                        codes = Array(codes);
                    }
                    codes.forEach(e => {
                        const oc = res.find(o => o.code === e);
                        if (oc != null) {
                            const f: SelectItem = {value: oc.code, label: oc.name};
                            this.oclist.push(f);
                        }
                        // else {
                        //     const f: SelectItem = {value: e, label: e};
                        //     this.oclist.push(f);
                        // }
                    });
                }

                this.authService.SelectedOcChanged.subscribe(s => {

                    if (this.allOcList.length === 0) {
                        this.operatingCentreService.Get().subscribe(res => {
                                if (res != null) {
                                    this.allOcList = res;
                                    // console.log("4567");
                                    // console.log(this.allOcList);

                                    this.allOcList.forEach(o => {
                                        if (o.code === this.authService.getSelectedOc()) {
                                            const f: SelectItem = {value: o.code, label: o.name};
                                            this.selectedoc = f;
                                        }
                                    });

                                    if (!this.selectedoc && this.oclist && this.oclist.length > 0) {
                                        this.selectedoc = this.oclist[0];
                                    }
                                }
                            });
                    } else {
                        this.allOcList.forEach(o => {
                            if (o.code === this.authService.getSelectedOc()) {
                                const f: SelectItem = {value: o.code, label: o.name};
                                this.selectedoc = f;
                            }
                        });

                        if (!this.selectedoc && this.oclist && this.oclist.length > 0) {
                            this.selectedoc = this.oclist[0];
                        }
                    }

                    this.updatenotificationbar();
                });

            });

            // ConnectionIndicationService.ConnectionStatusChanged.subscribe(status => {
            //     if (status) {
            //         // alert('start so fast?');
            //         this.selectedoc = this.authService.getSelectedOc();
            //         this.updatenotificationbar();
            //     }

            // });
        }
        );

    }

    updatenotificationbar() {
        // temporary remove notification:
        // this.ocBasedUnifiedNotificationService.GetStatusList().subscribe(statuslist => {
        //     this.ocBasedUnifiedNotificationService.InitiateCount(statuslist);
        // });
    }

    selectOc(x: SelectItem) {
        // console.log(x);
        this.authService.getEstimateEntryOnOcChange = true;
        this.authService.changeSelectedOc(x.value);
        this.authService.onChangeOcClick();
        this.userService.UpdateDefaultOcCode().subscribe(r => {
            this.changeOcRedirect();
        });
    }

    changeOcRedirect() {
        this.router.navigate(['/']);
    }

    hideMenu() {
        const dom: any = document.querySelector('body');
        dom.classList.toggle('hideMenu');

        if (this.hideMenuText === '<<') { this.hideMenuText = '>>'; } else { this.hideMenuText = '<<'; }
    }

    isToggled(): boolean {
        const dom: Element = document.querySelector('body');
        return dom.classList.contains(this.pushRightClass);
    }

    toggleSidebar() {
        const dom: any = document.querySelector('body');
        dom.classList.toggle(this.pushRightClass);
    }

    rltAndLtr() {
        const dom: any = document.querySelector('body');
        dom.classList.toggle('rtl');
    }

    onLoggedout() {
        this.authService.logOut();
        // localStorage.removeItem('isLoggedin');
    }

    onLoggedoutHide() {
        // console.log('sessionStorage.clear');
        // sessionStorage.clear();
        // localStorage.clear();
        this.authService.logOutComplete();
    }

    redirectLandingPage() {
        // this.ipmsUrl = this.UmUrl.substring(0, this.UmUrl.length - 1) + 'ui/#/module-selector';
        // console.log(this.UmUrl.substring(0, this.UmUrl.length - 1) + 'ui/#/module-selector');
        // window.open(this.UmUrl.substring(0, this.UmUrl.length - 1) + 'ui/#/module-selector','_self');
        window.open(AppConfig.settings.module_selector_url, '_self');
    }

    checkPermission(claim: string): boolean {
        return this.authService.hasPermissions(claim);
    }

}
