// 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 { WorksiteService } from '../../../providers/worksite.service';
import { WorksiteCmp, isCantiereChiuso } from '../../../models/worksite-cmp.model';

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

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

	ionViewWillEnter() {
		this.resolveIds();
		this.layout.setPageConfig({ title: 'Cantieri', 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;
		// ricerca server-side
		this.service.getWorksites(this.cmp_id, this.search || '').subscribe({
			next: (rows) => {
				this.cantieri = rows || [];
				this.loading = false;
				ev?.target?.complete();
			},
			error: () => {
				this.config.presentToastError('Errore nel caricamento dei cantieri');
				this.loading = false;
				ev?.target?.complete();
			},
		});
	}

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

	isChiuso(ws: WorksiteCmp): boolean {
		return isCantiereChiuso(ws);
	}

	statoLabel(ws: WorksiteCmp): string {
		// l'etichetta deriva dal codice stato (ws_stato_description dal backend è una classe CSS, non un testo)
		switch (ws.ws_stato) {
			case 2:
				return 'Chiuso';
			case 3:
				return 'Provvisorio';
			case 4:
				return 'Completato';
			case 5:
				return 'Sospeso';
			default:
				return 'Aperto';
		}
	}

	statoColor(ws: WorksiteCmp): string {
		if (ws.ws_stato === 2) return 'danger';
		if (ws.ws_stato === 5) return 'warning';
		return 'success';
	}

	openDetail(ws: WorksiteCmp) {
		this.router.navigate([`/portale/${this.prt_id}/company/${this.cmp_id}/service/cantieri/detail`, ws.ws_id]);
	}
}
