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 { LBRulesApiService } from '@fleio-api/openstack/load-balancing/rules/lb-rules-api.service';
import { ILBRuleModel } from '@fleio-api/openstack/load-balancing/model/lb-rule.model';

@Injectable({
  providedIn: 'root'
})
export class LbRuleListResolver implements Resolve<FleioObjectsList<ILBRuleModel>> {
  constructor(private lbRulesApiService: LBRulesApiService) {
  }

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