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

import { Casino } from '../models/casino';
import { CasinoPagination } from '../models/casino-pagination';
import { CasinoService } from '../services/casino.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Casino | undefined> {
    return this._casinoService.getCasinoById(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 CasinosResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _casinoService: CasinoService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: CasinoPagination;
    casinos: Casino[];
  }> {
    return this._casinoService.getCasinos();
  }
}
