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 { ILBMemberModel } from '@fleio-api/openstack/load-balancing/model/lb-member.model';
import { LBMembersApiService } from '@fleio-api/openstack/load-balancing/members/lb-members-api.service';

@Injectable({
  providedIn: 'root'
})
export class LbMemberListResolver implements Resolve<FleioObjectsList<ILBMemberModel>> {
  constructor(private lbMembersApiService: LBMembersApiService) {
  }

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