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

import { PartnerCalculate } from '../models/partner-calculate';
import { PartnerCalculatePagination } from '../models/partner-calculate-pagination';
import { PartnerCalculateService } from '../services/partner-calculate.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<PartnerCalculate | undefined> {
    return this._partnerCalculateService
      .getPartnerCalculateById(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 PartnerCalculatesResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _partnerCalculateService: PartnerCalculateService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: PartnerCalculatePagination;
    partnerCalculates: PartnerCalculate[];
  }> {
    return this._partnerCalculateService.getPartnerCalculates();
  }
}
