import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Injectable} from '@angular/core';
import {ApiService} from './api.service';
import {NavigationService} from './navigation.service';
import {DatabaseService} from './db/database.service';
import {LoadingController} from '@ionic/angular';

@Injectable({
    providedIn: 'root',
})
export class AuthService implements CanActivate {
    public authInProgress = false;

    constructor(
        protected readonly loader: LoadingController,
        protected readonly api: ApiService,
        protected readonly router: Router,
        protected readonly nav: NavigationService,
        protected readonly db: DatabaseService,
    ) { }

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

            if ( !isAuthenticated ) {
                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());
            }
        });
    }

    async endSession() {
        const loader = await this.loader.create({ message: 'Logging you out...' });
        await loader.present();

        await this.db.purge();
        await this.api.endSession();
        await this.router.navigate(['/login']);

        await loader.dismiss();
        this.nav.requestInitialization();
    }
}
