// 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 { WeeklyTemplate, AvailabilityException, OperatorSimple } from 'src/models/biz-appointments/availability.model';

@Injectable({
	providedIn: 'root',
})
export class BizAvailabilityService {
	constructor(private http: HttpClient, private configService: ConfigService) {}

	private get baseUrl(): string {
		return this.configService.serviceUrl_BizAppointments;
	}

	getWeeklyTemplates(cmp_id: number, operator_em_id?: number): Observable<WeeklyTemplate[]> {
		let url = `${this.baseUrl}availability/templates?cmp_id=${cmp_id}`;
		if (operator_em_id !== undefined && operator_em_id !== null) url += `&operator_em_id=${operator_em_id}`;

		return this.http.get(url, { observe: 'response' }).pipe(map((response: any) => response.body));
	}

	saveWeeklyTemplates(cmp_id: number, operator_em_id: number, templates: WeeklyTemplate[]): Observable<number> {
		return this.http
			.post(`${this.baseUrl}availability/templates/save?cmp_id=${cmp_id}&operator_em_id=${operator_em_id}`, templates, { observe: 'response' })
			.pipe(map((response: any) => response.body));
	}

	getExceptions(cmp_id: number, operator_em_id?: number, date_from?: string, date_to?: string): Observable<AvailabilityException[]> {
		let url = `${this.baseUrl}availability/exceptions?cmp_id=${cmp_id}`;
		if (operator_em_id) url += `&operator_em_id=${operator_em_id}`;
		if (date_from) url += `&date_from=${date_from}`;
		if (date_to) url += `&date_to=${date_to}`;

		return this.http.get(url, { observe: 'response' }).pipe(map((response: any) => response.body));
	}

	addException(exception: Partial<AvailabilityException>): Observable<number> {
		return this.http
			.post(`${this.baseUrl}availability/exceptions/add`, exception, { observe: 'response' })
			.pipe(map((response: any) => response.body));
	}

	deleteException(ae_id: number): Observable<number> {
		return this.http
			.delete(`${this.baseUrl}availability/exceptions/del/${ae_id}`, { observe: 'response' })
			.pipe(map((response: any) => response.body));
	}

	getOperators(cmp_id: number): Observable<OperatorSimple[]> {
		return this.http
			.get(`${this.baseUrl}availability/operators?cmp_id=${cmp_id}`, { observe: 'response' })
			.pipe(map((response: any) => response.body));
	}
}
