import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { InstancesApiService } from './instances-api.service';
import { IInstanceCreateOptions } from '../model/instance-create-options';

@Injectable({
  providedIn: 'root'
})
export class InstanceCreateOptionsResolver  {
  constructor(private instancesApiService: InstancesApiService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<IInstanceCreateOptions> | Promise<IInstanceCreateOptions> | IInstanceCreateOptions {
    const params = {}
    if (route.queryParams.image_id) {
      params['image'] = route.queryParams.image_id;
    }
    if (route.queryParams.region) {
      params['region'] = route.queryParams.region;
    }

    return this.instancesApiService.createOptions(params)
      .pipe(catchError(() => of(null))) as unknown as IInstanceCreateOptions;
  }
}
