import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ILBPolicyModel } from '@fleio-api/openstack/load-balancing/model/lb-policy.model';
import { LBPoliciesApiService } from '@fleio-api/openstack/load-balancing/policies/lb-policies-api.service';

@Injectable({
  providedIn: 'root'
})
export class LbPolicyListResolver implements Resolve<FleioObjectsList<ILBPolicyModel>> {
  constructor(private lbPoliciesApiService: LBPoliciesApiService) {
  }

  // noinspection JSUnusedLocalSymbols
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<FleioObjectsList<ILBPolicyModel>> | Promise<FleioObjectsList<ILBPolicyModel>> | FleioObjectsList<ILBPolicyModel> {
    let queryParams;
    this.lbPoliciesApiService.setAdditionalQueryParams(route.queryParams);
    if (route.params.loadBalancerId) {
      queryParams = {listener_id: route.params.id};
    } else {
      queryParams = {};
    }
    return this.lbPoliciesApiService.list(
      queryParams
    ).pipe(catchError(() => of(null)));
  }
}
