package ru.yandex.webmaster.common.addurl.dao;

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

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

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

/**
 * CREATE TABLE IF NOT EXISTS tbl_addurl_popular_hosts (
 *     backend_host VARCHAR(64) NOT NULL
 *   , date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
 *   , hostname VARCHAR(128) NOT NULL
 *   , request_count INT NOT NULL
 *
 *   , PRIMARY KEY (backend_host, hostname)
 *   , INDEX (date)
 * ) ENGINE=InnoDB;
 *
 * @author aherman
 */
public class TblAddUrlPopularHostsDao extends AbstractDbService {
    public List<PopularHostInfo> list(DateTime fromDate) throws InternalException {
        String q = "SELECT * FROM tbl_addurl_popular_hosts WHERE date > ?";
        return getJdbcTemplate(WMCPartition.nullPartition()).query(q, getMapper(), fromDate.toDate());
    }

    public void update(List<PopularHostInfo> popularHosts) throws InternalException {
        String q = "REPLACE tbl_addurl_popular_hosts SET backend_host = ?, hostname = ?, request_count = ?";
        for (PopularHostInfo popularHost : popularHosts) {
            getJdbcTemplate(WMCPartition.nullPartition()).update(q, popularHost.getBackendHost(),
                    popularHost.getHostname(), popularHost.getRequestCount());
        }
    }

    public void deleteOldHosts(LocalDate olderThan) throws InternalException {
        String q = "DELETE FROM tbl_addurl_popular_hosts WHERE date < ?";
        getJdbcTemplate(WMCPartition.nullPartition()).update(q, olderThan.toDate());
    }

    private ParameterizedRowMapper<PopularHostInfo> getMapper() {
        return new ParameterizedRowMapper<PopularHostInfo>() {
            @Override
            public PopularHostInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                String backendHost = rs.getString("backend_host");
                DateTime date = new DateTime(rs.getTimestamp("date"));
                String hostname = rs.getString("hostname");
                int requestCount = rs.getInt("request_count");

                return new PopularHostInfo(date, backendHost, hostname, requestCount);
            }
        };
    }
}
