import { Injectable } from '@angular/core';
import { Organization } from '../models/organization';
import { 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';

@Injectable({
  providedIn: 'root'
})
export class LogsService {

  time:number = 10000;

  constructor(private http: HttpClient) {
  }

  getEnergyProducedByParams(id:string, interval:string, date:string) {
    return this.http.get(`${environment.productionApiUrl}/asset/${id}/energy-produced/${interval}/${date}`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

  getEnergySummaryByAsset(id:string){
    return this.http.get(`${environment.productionApiUrl}/asset/${id}/energy-stats`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

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

  getEnergyProducedByWeek() {
    return this.http.get(`${environment.apiUrl}/logs/energyProduced/7D`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }
  
  getEnergyProducedByMonth() {
    return this.http.get(`${environment.apiUrl}/logs/energyProduced/1M`)
    .pipe(
      timeout(this.time),
      map(response =>{
        return response;
      }),
      catchError(this.errorHandl)
    )
  }

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

  //if(error.error instanceof ErrorEvent) {
  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);
  }
  
}
