import { Location, LocationStrategy } from '@angular/common';
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable, mergeMap, of } from 'rxjs';
import { Unsub } from '../class/unsub.class';
import { TranslatePipes } from '../pipes/translate/translate.pipe';
import { AdminService } from '../services/admin/admin.service';
import { LoaderService } from '../services/loader.service';
import { AdminDataService } from '../services/admin/admin-data.service';
import { TimeoutGuard } from './timeout.guard';

@Injectable({
  providedIn: 'root',
})
export class UserGuard extends Unsub implements CanActivate {
  constructor(
    public router: Router,
    private adminService: AdminService,
    private adminDataService: AdminDataService,
    private toastr: ToastrService,
    private translate: TranslatePipes,
    private location: Location,
    private timeoutGuard : TimeoutGuard,
    private locationStrategy: LocationStrategy,
    loaderService: LoaderService
  ) {
    super(loaderService);
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.checkAccess(route, state);
  }


  private checkAccess(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const data = this.getRouteData(route);
    return this.adminService.checkLoginAdmin().pipe(
      mergeMap(response => {        
    this.adminDataService.setSharedData(response?.body);
        let Twofactor = response.headers.get('Twofactor');
      const Google2fa = response.headers.get('Google2fa');
      const email = response.headers.get('email');
      if (Twofactor === 'admin') {
        this.router.navigate(['/admin/admintwofactor/' + email], {
          queryParams: {
            returnUrl: state.url,
          },
        });
        return of(false);
      } else if (Google2fa === 'admin') {
        this.router.navigate(['/admin/admingoogle2fa/' + email], {
          queryParams: {
            returnUrl: state.url,
          },
        });
        return of(false);
      } else
      
        if (response.body?.permissions) {
          localStorage.setItem('token', response.body.token);
          localStorage.setItem('user', JSON.stringify(response.body.user));
          localStorage.setItem('permissions', JSON.stringify(response.body.permissions));
          if (state.url.match('/admin/login')) {
            this.router.navigate(['/admin/dashboard']);
          }
          if (response.body?.user) {
            if(response?.body?.redirectionstatus){
              if(response.body.redirectionstatus == 'googletwofact'){
                this.router.navigate([`/admin/admingoogle2fa/${response.body?.email}`]);
              }else if(response.body.redirectionstatus == 'twofactoremail'){
                this.router.navigate([`/admin/admintwofactor/${response.body?.email}`]);
              }
              return of(false);
            }else{
              if (this.hasPermission(response.body, data, response.body)) {
                return this.timeoutGuard.canActivate(route, state);
              } else {
                if (this.location.getState() == null) {
                  this.location.back();
                } else {
                  this.router.navigate(['/admin/dashboard']);
                }
                this.toastr.error(this.translate.transform('You are Not Authorized to access this Page'));
                return of(false);
              }
            }
          } else {
            if (state.url !== '/admin/login' && !state.url.match('/admin/login')) {
              this.redirectToLoginPage(state.url);
            }
            return of(false);
          }
        } else {
          if (state.url.match('/admin/app-info/app-purchase-code')) {
            return of(true);
          }
          if (state.url.match('/admin/login')) {
            return of(true);
          }
          this.redirectToLoginPage(state.url);
          return of(false);
        }
      }));
  }

  getRouteData(route: ActivatedRouteSnapshot): any {
    if (route.data?.['permission']) {
      return route.data['permission'];
    }
    if (route.firstChild) {
      return this.getRouteData(route.firstChild);
    }
    return null;
  }

  private hasPermission(res: any, permission: boolean | string, response): boolean {
    if (response.ENVATO_ON == 'off') {
      if (permission == 'Envato Access' || permission == 'Envato API Token Access' || permission == 'Envato License Details Access') {
        return false;
      }
    }
    return permission === true || res.permissions?.includes(permission);
  }

  private redirectToLoginPage(returnUrl: string): void {
    if (!returnUrl || returnUrl === '/') {
      returnUrl = '/admin/dashboard';
    }

    this.router.navigate(['/admin/login'], {
      queryParams: {
        returnUrl,
      },
    });
  }

  canDeactivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    history.pushState(null, '');
    this.locationStrategy.onPopState(() => {
      history.go(1);
    });

    return true;
  }
}
