// Angular Core
import { Injectable  } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';

// RxJs
import { Observable } from 'rxjs';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';

// Services
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';
import { PageAuthorizationService } from 'src/app/services/pageAuthorization/page-authorization.service';
import { SearchService } from 'src/app/services/search/search.service';
import { SessionService } from 'src/app/services/session/session.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  session!: SessionDataInterface['data'];
  constructor(
    private sessionService: SessionService,
    private pageAuthorizationService : PageAuthorizationService,
    private searchService: SearchService,
    private router: Router,
    private localStorageService: LocalStorageService
    ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return new Promise(resolve => {
      let pageName = route.routeConfig?.path === undefined ? route.url[0].path : route.routeConfig?.path;
      let redirectedPage: string | null = this.localStorageService.getItem('redirectedPage');
      this.sessionService.getAuth().then(() => {
        this.session = this.sessionService.getSession()
        if (this.session.logged_in) {
          if( pageName !== redirectedPage  ){
            this.pageAuthorizationService.checkForPageAuthorization(this.session, pageName);
          }else{
            this.localStorageService.setItem('redirectedPage', pageName);
          }
          this.sessionService.checkGetAuthSession.emit(true);
          if(this.session.is_buyer){
            this.searchService.clearSearchInput.emit(true);
            this.searchService.resetAllToInitialState();
          }
          resolve(true);
        } else {
          this.router.navigate(['/market/login']);
          resolve(false);
        }
      })

    });
  }  

}
