import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { RoutersApiService } from '@fleio-api/openstack/routers/routers-api.service';
import { IRouterAddInterfaceCreateOptionsModel } from '@fleio-api/openstack/model/router-add-interface-create-options.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';

@Injectable({
  providedIn: 'root'
})
export class RouterAddInterfaceCreateOptionsResolver  {
  constructor(
    private routersApiService: RoutersApiService, private notificationService: NotificationService,
    private router: Router, private config: ConfigService,
  ) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<IRouterAddInterfaceCreateOptionsModel> | Promise<IRouterAddInterfaceCreateOptionsModel> |
    IRouterAddInterfaceCreateOptionsModel {
    return this.routersApiService.addInterfaceCreateOptions(route.params.id)
      .pipe(map(
        response => {
          if (!response.subnets?.length) {
            this.notificationService.showMessage($localize`No subnets available`);
            return this.router.navigateByUrl(
              this.config.getCurrentUrl()
            ).then(()=>{});
          }
          return response;
        }
      )) as unknown as IRouterAddInterfaceCreateOptionsModel;
  }
}
