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

import { CouponMoneyLog } from '../models/coupon-money-log';
import { CouponMoneyLogPagination } from '../models/coupon-money-log-pagination';
import { CouponMoneyLogService } from '../services/coupon-money-log.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<CouponMoneyLog | undefined> {
    return this._couponMoneyLogService
      .getCouponMoneyLogById(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 CouponMoneyLogsResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _couponMoneyLogService: CouponMoneyLogService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: CouponMoneyLogPagination;
    couponMoneyLogs: CouponMoneyLog[];
  }> {
    return this._couponMoneyLogService.getCouponMoneyLogs();
  }
}
