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

import { Withdraw } from '../models/withdraw';
import { WithdrawPagination } from '../models/withdraw-pagination';
import { WithdrawService } from '../services/withdraw.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Withdraw | undefined> {
    return this._withdrawService.getWithdrawById(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 WithdrawsResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _withdrawService: WithdrawService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: WithdrawPagination;
    withdraws: Withdraw[];
  }> {
    return this._withdrawService.getWithdraws();
  }
}
