import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import {ServiceResponse} from "../models/ServiceResponse";
import {map, tap} from "rxjs/operators";
import {HttpClient} from "@angular/common/http";
import {Form} from "../models/Form";

@Injectable({
    providedIn: 'root'
})
export class FormService {

    constructor(private http: HttpClient) {
    }

    public getForm(code?: string): Observable<Form> {
        return this.http.get<ServiceResponse<Form>>("lecservice/forms/" + code)
            .pipe(
                tap(
                    (serviceResponse: ServiceResponse<Form>) => {
                        if (!serviceResponse.success)
                            throw new Error(serviceResponse.messages?.join(", "));
                    }),
                map((serviceResponse: ServiceResponse<Form>) => {
                    return serviceResponse.success ? serviceResponse.result : null;
                })
            );
    }

    public postForm(data?: Form): Observable<String> {
        return this.http.post<ServiceResponse<String>>("lecservice/forms/save", data)
            .pipe(
                tap(
                    (serviceResponse: ServiceResponse<Form>) => {
                        if (!serviceResponse.success)
                            throw new Error(serviceResponse.messages?.join(", "));
                    }),
                map((serviceResponse: ServiceResponse<Form>) => {
                    return serviceResponse.success ? serviceResponse.result : null;
                })
            );
    }
}
