package ru.yandex.webmaster.viewer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.ReadablePeriod;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import ru.yandex.webmaster.viewer.service.SpammerDomainsCacheService;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.service.AbstractDbService;

/**
 * @author aherman
 */
public class TblCaptchaUsersDao extends AbstractDbService {
    public List<SpammerDomainsCacheService.GlobalCaptchaShows> listCaptchaUsers() throws InternalException {
        String q = "SELECT user_id, started, show_count FROM tbl_captcha_users";
        return getJdbcTemplate(WMCPartition.nullPartition()).query(q, getMapper());
    }

    public void removeExpiredUsers(ReadablePeriod olderThan) throws InternalException {
        DateTime olderTahnDate = DateTime.now().minus(olderThan);
        String q = "DELETE FROM tbl_captcha_users WHERE started < ?";
        getJdbcTemplate(WMCPartition.nullPartition()).update(q, olderTahnDate.toDate());
    }

    public void updateCaptchaShows(int localShowsDelta, SpammerDomainsCacheService.LocalCaptchaShows count)
            throws InternalException
    {
        String q =  "INSERT INTO tbl_captcha_users (user_id, started, show_count)" +
                    "  VALUES (?, ?, ?)" +
                    "  ON DUPLICATE KEY UPDATE show_count = show_count + ?";
        getJdbcTemplate(WMCPartition.nullPartition()).update(q, count.getUserId(), count.getFirstCaptchaDate().toDate(),
                count.getCount(), localShowsDelta);
    }

    private ParameterizedRowMapper<SpammerDomainsCacheService.GlobalCaptchaShows> getMapper() {
        return new ParameterizedRowMapper<SpammerDomainsCacheService.GlobalCaptchaShows>() {
            @Override
            public SpammerDomainsCacheService.GlobalCaptchaShows mapRow(ResultSet rs, int rowNum) throws SQLException {
                long userId = rs.getLong("user_id");
                Timestamp started = rs.getTimestamp("started");
                int showCount = rs.getInt("show_count");
                return new SpammerDomainsCacheService.GlobalCaptchaShows(userId, new DateTime(started), showCount);
            }
        };
    }
}
