import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FleioObjectsList } from '../../fleio-objects-list';
import { Observable, of } from 'rxjs';
import { IListQueryParams } from '../../base-model/list-query-params';
import { catchError } from 'rxjs/operators';
import { IProductModel } from '../model/product.model';
import { ProductsApiService } from './product-api.service';

@Injectable({
  providedIn: 'root'
})
export class ProductListResolver  {
  constructor(private productsApiService: ProductsApiService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<FleioObjectsList<IProductModel>> | Promise<FleioObjectsList<IProductModel>> |
    FleioObjectsList<IProductModel> {
    const queryParams = Object.assign({}, route.queryParams) as IListQueryParams;
    if (!queryParams.page_size) {
      queryParams.page_size = 1000000;
    }
    return this.productsApiService.list(
      queryParams
    ).pipe(catchError(() => of(null)));
  }
}
