/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Injectable} from '@angular/core';
import {CanActivate, NavigationExtras, Router, RouterStateSnapshot} from '@angular/router';
import {ActivatedProtectedRouteSnapshot} from './protected.routes';
import {AuthHelperService} from './auth-helper.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuardService implements CanActivate {
  constructor(
    private authHelper: AuthHelperService,
    private router: Router,
  ) {}

  public async canActivate(route: ActivatedProtectedRouteSnapshot, _state: RouterStateSnapshot) {
    if (route.queryParamMap.get('token')) {
      return true;
    }

    try {
      await this.authHelper.getProvider(route.data.authProvider).getValidToken();
    } catch {
      const originNavigation = this.router.getCurrentNavigation();
      let extras: NavigationExtras = {};
      if (originNavigation) {
        const url = originNavigation.extractedUrl.toString();
        extras = {queryParams: {origin_path: url}};
      }
      this.router.navigate(['profile'], extras);
      await this.authHelper.getProvider(route.data.authProvider).signIn();

      return false;
    }

    return true;
  }
}
