// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

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

import { ConfigService } from './config.service';
import { ImpiantoFv, PvDashboard } from 'src/app/models/fotovoltaico.model';

/**
 * Accesso ai dati del fotovoltaico (impianti + cruscotto energetico).
 * Riusa gli stessi endpoint del portale, esposti sul backend "companies"
 * (serviceUrl_Companies): pv-plant/list, pv-plant/get, pv-monitor/dashboard.
 */
@Injectable({ providedIn: 'root' })
export class FotovoltaicoService {
	constructor(
		private http: HttpClient,
		private config: ConfigService,
	) {}

	/** Lista impianti FV dell'azienda (scoping per cmp_id, come nel portale). */
	GetImpianti(cmp_id: number, txtsearch = ''): Observable<ImpiantoFv[]> {
		const url = `${this.config.serviceUrl_Companies}pv-plant/list?cmp_id=${cmp_id}&ws_id=0&txtsearch=${encodeURIComponent(txtsearch)}&order_by=&limit=1000&offset=0`;
		return this.http.get(url, { observe: 'response' }).pipe(map((response) => (response.body as ImpiantoFv[]) || []));
	}

	GetImpianto(pv_id: number): Observable<ImpiantoFv> {
		return this.http.get(`${this.config.serviceUrl_Companies}pv-plant/get?pv_id=${pv_id}`, { observe: 'response' }).pipe(map((response) => response.body as ImpiantoFv));
	}

	/** Cruscotto energetico del giorno indicato (formato day = yyyy-MM-dd). */
	GetDashboard(pv_id: number, day?: string): Observable<PvDashboard> {
		const d = day ? `&day=${day}` : '';
		return this.http
			.get(`${this.config.serviceUrl_Companies}pv-monitor/dashboard?pv_id=${pv_id}${d}`, { observe: 'response', responseType: 'text' })
			.pipe(map((response) => JSON.parse(response.body || '{}') as PvDashboard));
	}
}
