import { Inject, Injectable, Injector } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { sysConf } from '@conf/sys.conf';
import { CoreService } from '@core';
import { ACLGuard, ACLService } from '@delon/acl';
import { EAUserService } from '@shared';
import { Observable, of } from 'rxjs';

@Injectable()
export class EATokenGuard extends ACLGuard {
  constructor(srv: ACLService, router: Router, private eaUserSrv: CoreService, private router2: Router, private inject: Injector) {
    super(srv, router, inject);
  }

  canActivate(route: ActivatedRouteSnapshot, _state: RouterStateSnapshot | null): Observable<boolean> {
    const canOpen = this.eaUserSrv.loginStatus;
    if (!canOpen) {
      this.router2.navigate([sysConf.login_url], {
        queryParams: {
          returnUrl: _state?.url
        }
      });
      return of(!canOpen);
    }
    return super.canActivate(route, _state);
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const canOpen = this.eaUserSrv.loginStatus;
    if (!canOpen) {
      this.router2.navigate([sysConf.login_url], {
        queryParams: {
          returnUrl: state?.url
        }
      });
      return of(!canOpen);
    }
    return super.canActivateChild(childRoute, state);
  }
}
