import { Injectable, Inject } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot, Route, UrlSegment } from '@angular/router';
import { AuthorizeService } from './authorize.service';
import { Globals, LOGIN_PAGE } from './globals';
import { PageLoadingService } from './pageloading.service';
import { AppLogsService } from './applogs.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard  {
  constructor(
    private router: Router,
    private authService: AuthorizeService,
    private globals: Globals,
    private pageLoadingService: PageLoadingService,
    private appLogsService: AppLogsService
  ) { }

  canLoad(route: Route, segments: UrlSegment[]): boolean {
    return true;
  }


  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    let ret: boolean = true;
    const urlParsed: string[] = state.url.slice(1).split('/');
    if (!(this.authService.useJWT && !this.authService.checkJWT(0) && this.authService.isLoggedIn())) {
      const currentPageURL = urlParsed[0].split('?')[0];
      const currentPage = this.globals.getPage(currentPageURL);
      if (this.globals.isTheLoginPage(state.url/*'/' + currentpage*/) || this.authService.isLoggedIn()) {
        if (currentPage && currentPage.hidden && !currentPage.allowRedirect) return false; //security to acces hidden pages for unathorized
        let param: string = null;
        if (urlParsed.length > 1) param = urlParsed[urlParsed.length - 1];
        // if (currentPage?.allowRedirect && this.globals.currentPage === currentpage && !param) return false;
        if (this.globals.currentPage === currentPageURL) {
          if (currentPage.dontAllowEmptyURL && !param && !!this.globals.urlParam) {
            param = this.globals.urlParam;
            state.url += '/' + param;
            ret = false;
          }
        }
        this.globals.currentPage = currentPageURL;
        this.globals.urlParam = param;
        this.pageLoadingService.pageActive$.next(this.globals.urlParam);
        this.appLogsService.dlog('!! Goto', state.url);
        return ret;
      }
    } else {
      this.authService.expiredJWTLogout = true; //the flag is used to show jwt expired message
      if (await this.authService.tryRenewJWTAsync(false)) return true;
    }

    //not logged in and not in the logon page
    if (!this.globals.isTheLoginPage(state.url)) {
      const queryParams = { queryParams: { returnUrl: state.url } };
      this.globals.currentPage = LOGIN_PAGE.path;
      this.appLogsService.dlog('!! Goto ' + LOGIN_PAGE.path, state.url);
      this.router.navigate(['/' + LOGIN_PAGE.path], queryParams);
    }
    return false;
  }
}
