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;
import java.util.Set;

/**
 * User: azakharov
 * Date: 05.06.14
 * Time: 13:22
 */
public class TblAntispamSanctionsDao {
    private ClientFactory cassandraClientFactory;

    public boolean hasSanctions(final String hostName, final DateTime lastUpdateTime) {
        final CassandraClient client = cassandraClientFactory.getClientInstance();
        final Session s = client.getSession();
        final ResultSet rs = s.execute("SELECT sanctions, updated_on FROM webmaster.tbl_antispam_sanctions WHERE hostname = ?", hostName);
        final Iterator<Row> it = rs.iterator();
        if (!it.hasNext()) {
            return false;
        }
        final Row r = it.next();
        final Date updatedOn = r.getTimestamp("updated_on");
        final DateTime updatedOnDateTime = new DateTime(updatedOn.getTime());
        return !r.isNull("sanctions") &&
                (updatedOnDateTime.isAfter(lastUpdateTime) || updatedOnDateTime.isEqual(lastUpdateTime));
    }

    public void saveSanctions(final String hostName, final Set<String> sanctions, final Date now) {
        final CassandraClient client = cassandraClientFactory.getClientInstance();
        final Session s = client.getSession();
        // insert using TTL = 1 month
        s.execute("INSERT INTO webmaster.tbl_antispam_sanctions (hostname, sanctions, updated_on) " +
                  "VALUES (?,?,?) USING TTL 2678400 ", hostName, sanctions, now);
    }

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