package cz.senslog.connector.push.senslog;

import cz.senslog.connector.model.senslog.SensLogModel;
import cz.senslog.connector.push.api.ConnectorPusher;
import cz.senslog.connector.tools.http.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import static cz.senslog.connector.tools.http.HttpContentType.APPLICATION_JSON;

public class SensLogPusher implements ConnectorPusher<SensLogModel> {

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

    private final SensLogConfig config;
    private final HttpClient httpClient;

    public SensLogPusher(SensLogConfig config, HttpClient httpClient) {
        this.config = config;
        this.httpClient = httpClient;
    }

    @Override
    public void init() {}

    @Override
    public void push(SensLogModel model) {
        if (model == null || model.getPassThroughData() == null || model.getPassThroughData().isEmpty()) {
            logger.warn("Model has no observations."); return;
        }

        int successfullyPushed = 0;
        for (SensLogModel.PassingData data : model.getPassThroughData()) {

            URLBuilder urlBuilder = URLBuilder.newBuilder(config.getBaseUrl());
            data.getParams().forEach(urlBuilder::addParam);

            HttpRequest.Builder req = HttpRequest.newBuilder().POST()
                    .url(urlBuilder.build())
                    .contentType(APPLICATION_JSON)
                    .body(data.getPayload());

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

            if (res.isError()) {
                logger.error("Request error <{}> with reason: {}", res.getStatus(), res.getBody());
                continue;
            }

            if (res.isOk()) {
                logger.info("Pushed <{}> successfully: {}", res.getStatus(), res.getBody());
                successfullyPushed++;
            }

        }

        int totalSize = model.getPassThroughData().size();
        logger.info("Pushed {}/{} payloads. For the time <{} - {}>", successfullyPushed, totalSize, model.getFrom(), model.getTo());
    }
}
