// 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 { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '../../../providers/config.service';
import { LayoutService } from '../../../providers/layout.service';
import { FotovoltaicoService } from '../../../providers/fotovoltaico.service';
import { ImpiantoFv } from '../../../models/fotovoltaico.model';

@Component({
	selector: 'app-fotovoltaico-list',
	templateUrl: './fotovoltaico-list.page.html',
	styleUrls: ['./fotovoltaico-list.page.scss'],
	standalone: false,
})
export class FotovoltaicoListPage {
	cmp_id = 0;
	prt_id = 0;
	impianti: ImpiantoFv[] = [];
	search = '';
	private searchTimer: any;
	loading = false;

	constructor(
		private route: ActivatedRoute,
		private router: Router,
		private config: ConfigService,
		public layout: LayoutService,
		private service: FotovoltaicoService,
	) {}

	ionViewWillEnter() {
		this.resolveIds();
		this.layout.setPageConfig({ title: 'Fotovoltaico', showBack: true, backButtonHref: '/servizi' });
		this.load();
	}

	private resolveIds() {
		let r: ActivatedRoute | null = this.route;
		while (r) {
			const pm = r.snapshot.paramMap;
			if (pm.get('cmp_id')) this.cmp_id = +(pm.get('cmp_id') as string);
			if (pm.get('prt_id')) this.prt_id = +(pm.get('prt_id') as string);
			r = r.parent;
		}
	}

	load(ev?: any) {
		this.loading = true;
		this.service.GetImpianti(this.cmp_id, this.search || '').subscribe({
			next: (rows) => {
				this.impianti = rows || [];
				this.loading = false;
				ev?.target?.complete();
			},
			error: () => {
				this.config.presentToastError('Errore nel caricamento degli impianti');
				this.loading = false;
				ev?.target?.complete();
			},
		});
	}

	onSearch() {
		clearTimeout(this.searchTimer);
		this.searchTimer = setTimeout(() => this.load(), 350);
	}

	openCruscotto(p: ImpiantoFv) {
		this.router.navigate([`/portale/${this.prt_id}/company/${this.cmp_id}/service/fotovoltaico/cruscotto`, p.pv_id]);
	}
}
