import {ActivatedRoute, ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {ApiService} from '../api.service';
import {NavigationService} from '../navigation.service';
import {Injectable} from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class EditorGuard implements CanActivate {
    constructor(
        protected readonly api: ApiService,
        protected readonly router: Router,
        protected readonly nav: NavigationService,
    ) { }

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        const checkCanActivate = async () => {
            const PageId = route.paramMap.get('id');

            const canView = await this.api.checkPagePermission(String(PageId));

            if ( !canView ) {
                await this.router.navigate(['/login']);
                return false;
            } else {
                return true;
            }
        };

        return new Promise(async res => {
            if ( !this.nav.initialized$.getValue() ) {
                const sub = this.nav.initialized$.subscribe(async initialized => {
                    if ( initialized ) {
                        sub.unsubscribe();
                        return res(await checkCanActivate());
                    }
                });
            } else {
                return res(await checkCanActivate());
            }
        });
    }
}
