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

import { PartnerOffice } from '../models/partner-office';
import { PartnerOfficePagination } from '../models/partner-office-pagination';
import { PartnerOfficeService } from '../services/partner-office.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<PartnerOffice | undefined> {
    return this._partnerOfficeService
      .getPartnerOfficeById(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 PartnerOfficesResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _partnerOfficeService: PartnerOfficeService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: PartnerOfficePagination;
    partnerOffices: PartnerOffice[];
  }> {
    return this._partnerOfficeService.getPartnerOffices();
  }
}
