package ru.yandex.webmaster.common.antispam.sanctions.dao;

import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster.common.cassandra.CassandraClient;
import ru.yandex.webmaster.common.cassandra.ClientFactory;

import java.util.Date;
import java.util.Iterator;

/**
 * User: azakharov
 * Date: 09.06.14
 * Time: 12:55
 */
public class TblAntispamSanctionsUpdateControlDao {
    private ClientFactory cassandraClientFactory;

    public DateTime getLastUpdateTime() {
        try (CassandraClient client = cassandraClientFactory.createClient()) {
            final Session s = client.getSession();
            final ResultSet rs = s.execute(
                    "SELECT last_update_time FROM webmaster.tbl_antispam_sanctions_update_control WHERE id = 0");
            Iterator<Row> it = rs.iterator();
            if (!it.hasNext()) {
                return new DateTime();
            }
            final Row r = it.next();
            final Date d = r.isNull("last_update_time") ? new Date() : r.getTimestamp("last_update_time");
            return new DateTime(d.getTime());
        }
    }

    public void saveLastUpdateTime(final Date lastUpdateTime) {

        final DateTime previousLastUpdateTime = getLastUpdateTime();

        try (CassandraClient client = cassandraClientFactory.createClient()) {
            final Session s = client.getSession();
            // insert new row
            s.execute("INSERT INTO webmaster.tbl_antispam_sanctions_update_control (id, last_update_time) " +
                    "VALUES (0, ?)", lastUpdateTime);
        }
    }

    @Required
    public void setCassandraClientFactory(ClientFactory cassandraClientFactory) {
        this.cassandraClientFactory = cassandraClientFactory;
    }
}
