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

import { CustomerTemplate } from '../models/ customer-template';
import { CustomerTemplatePagination } from '../models/customer-template-pagination';
import { CustomerTemplateService } from '../services/customer-template.service';

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

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<CustomerTemplate | undefined> {
    return this._customerTemplateService
      .getCustomerTemplateById(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 CustomerTemplatesResolver implements Resolve<any> {
  /**
   * Constructor
   */
  constructor(private _customerTemplateService: CustomerTemplateService) {}

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

  /**
   * Resolver
   *
   * @param route
   * @param state
   */
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<{
    pagination: CustomerTemplatePagination;
    customerTemplates: CustomerTemplate[];
  }> {
    return this._customerTemplateService.getCustomerTemplates();
  }
}
