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

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

    async canActivate(): Promise<boolean> {
        const checkCanActivate = async () => {
            const isAuthenticated = (this.api.isAuthenticated && !this.api.isPublicUser);

            if ( isAuthenticated ) {
                await this.router.navigate(['/home']);
                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());
            }
        });
    }
}
