import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { take, map } from 'rxjs/operators';

import { WEB_SERVICE_CONFIG } from 'app/core/provider-name-token';
import { WebServiceConfig } from 'app/core/web-service-config';

import { SystemConfig, SystemAttributes } from './system-config';
import { FunctionConfig, FunctionAttributes } from './function-config';
import { ServiceConfig, ServiceAttributes } from './service-config';
import { LayerConfig, LayerAttributes } from './layer-config';
import { GeneralConfig } from './general-config';

@Injectable()
export class AppConfigService {

  system: SystemConfig = null;
  function: FunctionConfig = null;
  service: ServiceConfig = null;
  layer: LayerConfig = null;
  general: GeneralConfig = null;

  constructor(
    private http: HttpClient,
    @Inject(WEB_SERVICE_CONFIG) private webServiceConfig: WebServiceConfig
  ) {
    (window as any).appConfigService = this;
  }

  public load(): Promise<any> {
    const appConfigEndPoint = `${this.webServiceConfig.webServiceUrl}/${this.webServiceConfig.appConfigPath}`;
    return this.http.get<any>(appConfigEndPoint)
      .pipe(take(1))
      .pipe(map((configResponse) => {
        if (configResponse.success === true) {
          this.system = new SystemConfig(configResponse.data);
          this.function = new FunctionConfig(configResponse.data2);
          this.service = new ServiceConfig(configResponse.data3);
          this.layer = new LayerConfig(configResponse.data4);
          this.general = new GeneralConfig(configResponse.data5);
        }
        return configResponse;
      })).toPromise();
  }

  public getSystemFromId(systemId: string): SystemAttributes | null {
    return this.system.systems.find(systemAttributes => systemAttributes.SYSTEM_ID === systemId) || null;
  }

  public getFunctionsFromSystemId(systemId: string): FunctionAttributes[] {
    return this.function.functions.filter(functionAttributes => functionAttributes.SYSTEM_ID === systemId);
  }

  public getFunctionFromId(functionId: string): FunctionAttributes | null {
    return this.function.functions.find(functionAttributes => functionAttributes.FUNCTION_ID === functionId) || null;
  }

  public getServicesFromSystemId(systemId: string): ServiceAttributes[] {
    return this.service.services.filter(serviceAttributes => serviceAttributes.SYSTEM_ID === systemId);
  }

  public getServiceFromId(serviceId: string): ServiceAttributes | null {
    return this.service.services.find(serviceAttributes => serviceAttributes.SERVICE_ID === serviceId) || null;
  }

  public getLayersFromServiceId(serviceId: string): LayerAttributes[] {
    return this.layer.layers.filter(layerAttributes => layerAttributes.SERVICE_ID === serviceId);
  }

  public getLayerFromId(layerId: number): LayerAttributes | null {
    return this.layer.layers.find(layerAttributes => layerAttributes.LAYER_ID === layerId) || null;
  }

}
