package cz.senslog.analytics.module;

import cz.senslog.analytics.domain.ThresholdViolationAlert;
import cz.senslog.analytics.module.api.SimpleModule;
import cz.senslog.analytics.repository.AnalyticsRepository;
import io.vertx.core.Promise;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Arrays;


public final class AlertModule extends SimpleModule {

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

    private final AnalyticsRepository repo;

    private String alertServiceURL;


    public AlertModule(AnalyticsRepository repo) {
        this.repo = repo;
    }

    @Override
    public void configure(Promise<Void> completePromise) {
        alertServiceURL = config().getJsonObject("modules").getString("alert.service.url");
        completePromise.complete();
    }

    @Override
    public void run(Promise<Void> completePromise) {
        vertx.eventBus().<ThresholdViolationAlert>consumer(id(), msg -> vertx.executeBlocking(() -> blockingAlertHandler(msg.body()))
                        .onSuccess(res -> logger.info("Alert sent successfully!"))
                        .onFailure(logger::error))
                .completionHandler(ar -> {
                    if (ar.succeeded()) {
                        completePromise.complete();
                    } else {
                        completePromise.fail(ar.cause());
                    }
                });
    }

    private Object blockingAlertHandler(ThresholdViolationAlert alert) {
        logger.info("Sending the alert: Title: {}, Message: {}, At: {} to {}.", alert.sourceName(), Arrays.toString(alert.violatedData()), alert.timestamp(), alertServiceURL);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // TODO send the alert
        return null;
    }
}