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

import { PartnerRecommendation } from '../models/partner-recommendation';
import { PartnerRecommendationPagination } from '../models/partner-recommendation-pagination';
import { PartnerRecommendationService } from '../services/partner-recommendation.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<PartnerRecommendation | undefined> {
    return this._partnerRecommendationServiceService
      .getPartnerRecommendationById(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 PartnerRecommendationsResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(
    private _partnerRecommendationService: PartnerRecommendationService
  ) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: PartnerRecommendationPagination;
    partnerRecommendations: PartnerRecommendation[];
  }> {
    return this._partnerRecommendationService.getPartnerRecommendations();
  }
}
