import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";

import {Observable} from "rxjs";
import {map, tap} from "rxjs/operators";

import {Page} from "../models/Page";
import {Parameter} from "../models/Parameter";
import {ServiceResponse} from "../models/ServiceResponse";
import { ParametricQuery } from "../models/enea/ParametricQuery";

import {DatasourceConfiguration} from "../widgets/Widget";

import {ParameterResolverService} from "./parameter-resolvers/parameter-resolver.service";

import {UtilsService} from "./utils.service";


@Injectable({
    providedIn: 'root'
})
export class DataService {
	
    constructor(private http: HttpClient, private parameterResolver: ParameterResolverService, private utils: UtilsService) {}
    
    public getData(configuration: DatasourceConfiguration): Observable<any> {

        console.log("GetData Configuration : " + JSON.stringify( configuration ));

        const data = {
            "queryId": configuration.parametricQuery?.queryid,
            "parameters": configuration.parameters.map(o => <Parameter>{ name: o.name, value: this.parameterResolver.resolve(o) })
        };
        
        return this.http.post("lecservice/data/getData", data).pipe(
            tap(
                (serviceResponse: ServiceResponse<any>) => {
                    if (!serviceResponse.success)
                        throw new Error(serviceResponse.messages?.join(", "));
                })
            ,
            map((serviceResponse: ServiceResponse<Page>) => {
                return serviceResponse.success ? serviceResponse.result : null;
            })
        );
    }

    public areParametersFilled(configuration: DatasourceConfiguration) {
        if (configuration && configuration.parameters.length > 0 && configuration.parameters.some(o => {
            const result = this.utils.isBlank(this.parameterResolver.resolve(o));
            if (result) console.info("Parametro vuoto: ", o);
            return result
        }))
            return false;

        return true;
    }

    public getListOfFunctions(): Observable<ParametricQuery[]> {
        return this.http.get<ParametricQuery[]>("lecservice/data/admin/getListOfFunctions");
    }
}