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

import { Monthly } from '../models/monthly';
import { MonthlyPagination } from '../models/monthly-pagination';
import { MonthlyService } from '../services/monthly.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Monthly | undefined> {
    return this._monthlyService.getMonthlyById(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 MonthlysResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _monthlyService: MonthlyService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: MonthlyPagination;
    monthlys: Monthly[];
  }> {
    return this._monthlyService.getMonthlys();
  }
}
