package cz.senslog.analytics.repository;

import cz.senslog.analytics.domain.StatisticRecord;
import io.vertx.core.Future;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.Tuple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public final class AnalyticsDataRepository {

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

    private final Pool client;

    public AnalyticsDataRepository(Pool client) {
        this.client = client;
    }

    public Future<Integer> saveStatisticRecord(StatisticRecord record) {
        if (record == null) { return Future.failedFuture("StatisticRecord to save is null."); }
        return client.preparedQuery("INSERT INTO analytics.records(group_id, value_attribute, record_value, time_interval, time_stamp) " +
                        "VALUES ($1, $2, $3, $4, $5) RETURNING (id)")
                .execute(Tuple.of(record.groupId(),
                        record.valueAttribute(),
                        record.recordValue(),
                        record.timeInterval(),
                        record.timestamp()
                ))
                .map(rs -> rs.iterator().next().getInteger("id"))
                .onFailure(logger::error);
    }
}
