package cz.senslog.connector.fetch.openmeteo;

import com.google.gson.JsonObject;
import cz.senslog.connector.fetch.api.ConnectorFetcher;
import cz.senslog.connector.model.api.VoidSession;
import cz.senslog.connector.model.openmeteo.OpenMeteoModel;
import cz.senslog.connector.tools.http.HttpClient;
import cz.senslog.connector.tools.http.HttpRequest;
import cz.senslog.connector.tools.http.HttpResponse;
import cz.senslog.connector.tools.http.URLBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static cz.senslog.connector.tools.json.BasicJson.jsonToObject;

public class OpenMeteoFetcher implements ConnectorFetcher<VoidSession, OpenMeteoModel> {

    private static final Logger logger = LogManager.getLogger(OpenMeteoFetcher.class);

    private final HttpClient httpClient;
    private final OpenMeteoConfig config;

    public OpenMeteoFetcher(OpenMeteoConfig config, HttpClient httpClient) {
        this.httpClient = httpClient;
        this.config = config;
    }

    @Override
    public void init() throws Exception {

    }

    @Override
    public OpenMeteoModel fetch(Optional<VoidSession> session) {

        List<JsonObject> results = new ArrayList<>(config.getStations().size());

        for (OpenMeteoConfig.Station station : config.getStations()) {

            HttpRequest.Builder req = HttpRequest.newBuilder().GET()
                    .url(URLBuilder.newBuilder(config.getUrl())
                            .addParam("latitude", Double.toString(station.latitude))
                            .addParam("longitude", Double.toString(station.longitude))
                            .addParam("timezone", station.timezone)
                            .addParam("past_days", Integer.toString(station.past_days))
                            .addParam("hourly", String.join(",", station.hourly))
                            .build());

            HttpResponse res = httpClient.send(req.build());

            if (res.isError()) {
                logger.warn("Open Meteo station lat: {}, lon: {} failed to fetch. Error: {}", station.latitude, station.longitude, res.getBody());
                continue;
            }

            JsonObject geoJson = jsonToObject(res.getBody(), JsonObject.class);
            results.add(geoJson);
        }

        return new OpenMeteoModel(null, null, results);
    }
}
