import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Resolve,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { catchError, Observable, throwError } from 'rxjs';

import { Evolution } from '../models/evolution';
import { EvolutionPagination } from '../models/evolution-pagination';
import { EvolutionService } from '../services/evolution.service';

@Injectable({
  providedIn: 'root',
})
export class EvolutionResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(
    private _evolutionService: EvolutionService,
    private _router: Router
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Evolution | undefined> {
    return this._evolutionService
      .getEvolutionById(route.paramMap.get('id'))
      .pipe(
        // Error here means the requested product is not available
        catchError((error) => {
          // Log the error
          console.error(error);

          // Get the parent url
          const parentUrl = state.url.split('/').slice(0, -1).join('/');

          // Navigate to there
          this._router.navigateByUrl(parentUrl);

          // Throw an error
          return throwError(error);
        })
      );
  }
}

@Injectable({
  providedIn: 'root',
})
export class EvolutionsResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _evolutionService: EvolutionService) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: EvolutionPagination;
    evolutions: Evolution[];
  }> {
    return this._evolutionService.getEvolutions();
  }
}
