import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {Authorization} from 'src/app/models/Authorization';
import {Page} from "src/app/models/Page";
import {UserService} from 'src/app/services/user.service';
import {takeWhile} from "rxjs/operators";
import {PageService} from 'src/app/services/page.service';
import {Subscription} from 'rxjs';
import {UtilsService} from 'src/app/services/utils.service';
import {LanguageService} from "../../services/language.service";
import {AuthService} from "../../services/auth.service";
import {DropdownChangeEvent} from "primeng/dropdown";


@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit, OnDestroy {
    title = 'lec';

    slug: string = "";
    pages: Page[] = [];
    alive: boolean = true;

    disposeOnDestroySubscriptions: Subscription[] = [];
    lastLoadedLang: string | null = null;
    isAdmin: boolean = false;
    isManager: boolean = false;

    constructor(
        private route: ActivatedRoute,
        public translate: TranslateService,
        private router: Router,
        public userService: UserService,
        private authService: AuthService,
        private pageService: PageService,
        private utilService: UtilsService,
        private languageService: LanguageService
    ) {
    }

    login() {
        this.userService.login();
    }

    ngOnDestroy() {
        this.alive = false;
        for (const subscription of this.disposeOnDestroySubscriptions)
            subscription.unsubscribe();
    }

    ngOnInit(): void {
        this.disposeOnDestroySubscriptions.push(
            this.authService.onAuthChange()
                .pipe(takeWhile(() => this.alive))
                .subscribe((authorization: Authorization) => {
                    if (this.userService.user && !this.userService.user.newUser) {
                        this.setUserProperties();
                        this.loadPages();
                    }
                    this.lastLoadedLang = this.languageService.getLanguage();
                }),

            this.translate.onLangChange.subscribe(lang => {
                    const langHasChanged = lang.lang !== this.lastLoadedLang;

                    if (this.userService.user && langHasChanged) {
                        this.loadPages();
                    }
                    this.lastLoadedLang = lang.lang;
                }
            )
        );
    }

    loadPages() {
        this.pageService.getUserPages().subscribe(pages => {
            this.pages = pages;
        });
    }

    setUserProperties() {
        for (let authority of this.userService?.user?.authorities) {
            if (authority.authority === 'admin') this.isAdmin = true;
        }

        for (let role of this.userService?.user?.userroles) {
            if (this.userService?.selectedCommunity === role.communityID && role.roleID === 7)
                this.isManager = true;
        }

    }

    logout() {
        this.pages = [];
        this.router.resetConfig(this.router.config.filter(o => !o.data || !o.data.dynamic));
        this.isAdmin = false;
        this.isManager = false;
        // Detach from ngZone
        setTimeout(() => this.authService.removeAuthorization(), 200);
    }

    setActualLanguage(lang: string) {
        this.languageService.setLanguage(lang);
    }

    public goToPage(slug: string) {
        this.slug = slug;
        if (slug)
            this.pageService.getPageConfiguration(slug);
    }

    /*setCommunity(event: Event) {*/
    setCommunity(event: DropdownChangeEvent) {
        this.registerParams("communityid", this.userService.community.communityid);
        this.userService.selectedCommunity = (this.userService?.community?.communityid || -1) as Number;
    }

    registerParams(paramName: string, value?: string) {
        let queryParams: any = {};
        queryParams[paramName] = value;

        this.router.navigate([], {
            relativeTo: this.route,
            queryParams: queryParams,
            queryParamsHandling: 'merge',
            skipLocationChange: false
        });
    }

}
