import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RegionsApiService } from '@fleio-api/openstack/region/regions-api.service';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { IRegionModel } from '@fleio-api/openstack/model/region.model';

@Injectable({
  providedIn: 'root'
})
export class RegionService {
  public regions: IRegionModel[];

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private regionsApi: RegionsApiService) {
  }

  private getRouteRegionOrDefault(regionSelectorDefaultRegionKey?: string) {
    if (this.regions) {
      let defaultRegion: IRegionModel;

      if (regionSelectorDefaultRegionKey) {
        defaultRegion = this.regions.find(r => r.hasOwnProperty(
          regionSelectorDefaultRegionKey) && r[regionSelectorDefaultRegionKey]
        );
      }

      if (!defaultRegion) {
        defaultRegion = this.regions.find(r => r.is_default);
      }
      if (!defaultRegion) {
        defaultRegion = this.regions[0];
      }

      // look for region in query params
      const routeQueryParams = this.activatedRoute.snapshot.queryParams;
      const selectedRegion = routeQueryParams?.region ? routeQueryParams.region : defaultRegion.id;

      return selectedRegion;
    } else {
      return null;
    }
  }

  public getSelectedRegion(regionSelectorDefaultRegionKey?: string): Observable<string> {
    if (!this.regions) {
      return this.regionsApi.list({page_size: 1000}).pipe(map(regionList => {
        this.regions = regionList.objects;

        const selectedRegion = this.getRouteRegionOrDefault(regionSelectorDefaultRegionKey);
        return selectedRegion;
      }));
    } else {
      const selectedRegion = this.getRouteRegionOrDefault(regionSelectorDefaultRegionKey);
      return of(selectedRegion);
    }
  }

  public setRegion(region: string) {
    const queryParams = {region: undefined};
    Object.assign(queryParams, this.activatedRoute.snapshot.queryParams);
    queryParams.region = region;
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams
    }).catch(() => {
      // error has to be handled by interceptor, or where the request is done
    });
  }
}
