import { Injectable } from '@angular/core';
import { HttpParams, HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, Observable, throwError, tap } from 'rxjs';
import { ApiService } from './api.service';
import { ApiResponse } from '../interface/sensor-data';
import { StorageService } from './storage.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class SensorService extends ApiService {
  constructor(http: HttpClient, 
    private storageService: StorageService, 
    private toast: ToastrService) {
    super(http);
  }

  private getDataUrl = `${this.baseUrl}api/sensor/getData`;
  private getLatestUrl = `${this.baseUrl}api/sensor/getLatest`;
  private getStatusRelay = `${this.baseUrl}api/relay/get-relay`;

  private createAuthHeaders(): HttpHeaders {
    const token = this.storageService.getToken();  
    return new HttpHeaders({
      Authorization: `Bearer ${token}`
    });
  }

  getSensorDataHourly(sensor: string, metric: string, start: string, end: string, timeRange: string): Observable<ApiResponse> {
    const params = new HttpParams()
        .set('range[start]', start)
        .set('range[end]', end)
        .set('range[time_range]', timeRange)
        .set('sensor', sensor)
        .set('metric', metric);

    const headers= this.createAuthHeaders();

    return this.http.get<ApiResponse>(this.getDataUrl, { params, headers }).pipe(
      catchError(error => {
        // this.toast.error('Failed to get sensor data for graphic, please try again');
        return throwError(error);
      })
    );
  }

  getSensorDataDaily(sensor: string, metric: string, start: string, end: string, timeRange: string): Observable<ApiResponse> {
    const params = new HttpParams()
        .set('range[start]', start)
        .set('range[end]', end)
        .set('range[time_range]', timeRange)
        .set('sensor', sensor)
        .set('metric', metric);

    const headers= this.createAuthHeaders();

    return this.http.get<ApiResponse>(this.getDataUrl, { params, headers }).pipe(
      catchError(error => {
        // this.toast.error('Failed to get sensor data for graphic, please try again');
        return throwError(error);
      })
    );
  }

  getLatestData(): Observable<ApiResponse> {
    const headers = this.createAuthHeaders();

    return this.http.get<any>(this.getLatestUrl, { headers }).pipe(
      catchError(error => {
        // this.toast.error('Failed to get latest sensor data, please try again');
        return throwError(error);
      })
    );
  }

  getRelayStatus(): Observable<ApiResponse> {
    const headers = this.createAuthHeaders();

    return this.http.get<any>(this.getStatusRelay, { headers }).pipe(
      catchError(error => {
        // this.toast.error('Failed to get relay status, please try again');
        return throwError(error);
      })
    );
  }
}
