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

import { Daily } from '../models/daily';
import { DailyPagination } from '../models/daily-pagination';
import { DailyService } from '../services/daily.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Daily | undefined> {
    return this._dailyService.getDailyById(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 DailysResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _dailyService: DailyService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: DailyPagination;
    dailys: Daily[];
  }> {
    return this._dailyService.getDailys();
  }
}
