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

import { PartnerMainoffice } from '../models/partner-mainoffice';
import { PartnerMainofficePagination } from '../models/partner-mainoffice-pagination';
import { PartnerMainofficeService } from '../services/partner-mainoffice.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<PartnerMainoffice | undefined> {
    return this._partnerMainofficeService
      .getPartnerMainofficeById(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 PartnerMainofficesResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _partnerMainofficeService: PartnerMainofficeService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: PartnerMainofficePagination;
    partnerMainoffices: PartnerMainoffice[];
  }> {
    return this._partnerMainofficeService.getPartnerMainoffices();
  }
}
