package cz.senslog.connector.push.telemetry;

import cz.senslog.connector.model.telemetry.TelemetryModel;
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;

import java.util.Map;

import static java.lang.String.format;

public class TelemetryPusher implements ConnectorPusher<TelemetryModel> {

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


    private final TelemetryConfig config;

    private final HttpClient httpClient;

    public TelemetryPusher(final TelemetryConfig config, final HttpClient httpClient) {
        this.config = config;
        this.httpClient = httpClient;
    }

    @Override
    public void init() throws Exception {
        HttpRequest request = HttpRequest.newBuilder().GET()
                .url(URLBuilder.newBuilder(config.getInfoUrl()).build())
                .build();

        HttpResponse response = httpClient.send(request);

        if (response.isError()) {
            throw logger.throwing(new Exception(format(
                    "Can not get information about the telemetry instance. %s", response.getBody()
            )));
        }

        String responseBody = response.getBody();
        Map<?, ?> infoJson = BasicJson.jsonToObject(responseBody, Map.class);
        logger.info(format("Successfully connected to: %s", infoJson.get("name")));
    }

    @Override
    public void push(TelemetryModel model) {
        logger.info(format("Pushing: %s", model.getBody()));
    }
}