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

import { DailyPartner } from '../models/daily-partner';
import { DailyPartnerPagination } from '../models/daily-partner-pagination';
import { DailyPartnerService } from '../services/daily-partner.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<DailyPartner | undefined> {
    return this._dailyPartnerService
      .getDailyPartnerById(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 DailyPartnersResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _dailyPartnerService: DailyPartnerService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: DailyPartnerPagination;
    dailyPartners: DailyPartner[];
  }> {
    return this._dailyPartnerService.getDailyPartners();
  }
}
