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

import { TodayBet } from '../models/today-bet';
import { TodayBetPagination } from '../models/today-bet-pagination';
import { TodayBetService } from '../services/today-bet.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<TodayBet | undefined> {
    return this._todayBetService.getTodayBetById(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 TodayBetsResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _todayBetService: TodayBetService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    todayBets: TodayBet[];
  }> {
    return this._todayBetService.getTodayBets();
  }
}
