package cz.senslog.connector.push.analytics;

import cz.senslog.connector.model.analytics.AnalyticsModel;
import cz.senslog.connector.push.api.ConnectorPusher;
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 cz.senslog.connector.tools.json.BasicJson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class AnalyticsPusher implements ConnectorPusher<AnalyticsModel> {

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

    private final AnalyticsConfig config;
    private final HttpClient httpClient;


    public AnalyticsPusher(AnalyticsConfig config, HttpClient httpClient) {
        this.config = config;
        this.httpClient = httpClient;
    }

    @Override
    public void init() throws Exception {

    }

    @Override
    public void push(AnalyticsModel model) {
        if (model == null || model.getObservations() == null || model.getObservations().isEmpty()) {
            logger.warn("Nothing to push. The model is empty."); return;
        }

        HttpRequest request = HttpRequest.newBuilder().POST()
                .url(URLBuilder.newBuilder(config.getUrl()).build())
                .header("Content-Type", "application/json")
                .body(BasicJson.objectToJson(model.getObservations()))
                .build();
        HttpResponse response = httpClient.send(request);

        if (response.isOk()) {
            logger.info("Successfully uploaded to the SensLog Analytics. {}", response.getBody());
        } else {
            logger.error("SensLog Analytics Failed. The reason {}.", response.getBody());
        }

    }
}
