// Copyright (c) 2020 UWB & LESP.
// The UWB & LESP license this file to you under the MIT license.

package cz.senslog.connector.push.afarcloud;

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.model.afarcloud.AFarCloudModel;
import cz.senslog.connector.model.afarcloud.MultiMeasurement;
import cz.senslog.connector.model.config.HostConfig;
import cz.senslog.connector.push.api.ConnectorPusher;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.UUID;



public class AFarCloudPusher implements ConnectorPusher<AFarCloudModel> {

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

    private final AFarCloudConfig config;
    private final HttpClient httpClient;

    AFarCloudPusher(AFarCloudConfig config, HttpClient httpClient) {
        this.config = config;
        this.httpClient = httpClient;
    }

    @Override
    public void init() {}

    @Override
    public void push(AFarCloudModel model) {

        if (model == null || model.getUnitAggObservations() == null) {
            logger.warn("Nothing to push. The model is empty."); return;
        }

        HostConfig host = config.getTelemetryHost();

        int counter = 0;
        for (MultiMeasurement aggObservations : model.getUnitAggObservations()) {

            String id = UUID.randomUUID().toString();
            logger.info("Observation {} {}", id, aggObservations);

            logger.debug("Creating a request for the observation {}.", id);
            HttpRequest request = HttpRequest.newBuilder().POST()
                    .url(URLBuilder.newBuilder(host.getDomain(), host.getPath())
//                            .addParam("test", "")
                            .build())
                    .body(aggObservations.toJson())
                    .build();

            logger.info("Sending request for the {}", id);
            HttpResponse response = httpClient.send(request);
            logger.info("Response of {} with status {}.", id, response.getStatus());

            if (response.isOk()) {
                counter += 1;
                logger.info("Observation with id {} was uploaded successfully.", id);
            } else {
                logger.error("Observation with id {} was not send. Reason {}.", id, response.getBody());
            }
        }

        logger.info("Total uploaded multiple observation {}/{}.", counter, model.getUnitAggObservations().size());
    }
}