import { Injectable } from '@angular/core';
import { Organization } from '../models/organization';
import { PlantData, Plant } from '../models/plant';

import { of as observableOf, Observable, throwError } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { retry, catchError, map, timeout } from 'rxjs/operators';

import { environment } from '@environments/environment';

import { plantsData } from '../data/plants.data';

@Injectable({
  providedIn: 'root'
})
export class PlantsService extends PlantData {

  private listData: Plant[] = plantsData;
  
  time:number = 10000;

  constructor(private http: HttpClient) {
    super();
  }

  getInstalledCapacity() {
    return this.http.get(`${environment.apiUrl}/metersInstalled/installedCapacityTotal`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

  getAllAssets(){
    return this.http.get<any>(`${environment.productionApiUrl}/assets`, {})
    .pipe(
      map(response => {
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

  getAssetById(assetId:string){
    return this.http.get<any>(`${environment.productionApiUrl}/asset/${assetId}`, {})
    .pipe(
      map(response => {
        return response;
      }),
      catchError(this.errorHandl)
    )
  }


  getAssets() {
    return this.http.get(`${environment.apiUrl}/assets`)
    .pipe(
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

  //getAsset(id: string) {
    //return observableOf(this.listData.find(e => e.id === id));
  //}

  
  getAssetsProducedEnergy() {
    return this.http.get(`${environment.apiUrl}/assets/energyProduced`)
    .pipe(
      timeout(this.time),
      map( response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

  getPlants() {
    return observableOf(this.listData);
  }

  getPlant(id: number) {
    return observableOf(this.listData.find(e => e.id === id));
  }

 
  

  getOrganizationPlants(id:string)  {
    return this.http.get<any>(`${environment.apiUrl}/assets/${id}`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }
  
  errorHandl(error) {
    let errorMessage = '';
    if(error.error) {
      // Get client-side error
      errorMessage = error.error;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;      
    }
    return throwError(errorMessage);
 }

}
