package ru.yandex.wmconsole.service.dao;

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

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

import ru.yandex.wmconsole.data.info.SearchUpdateIntervalInfo;
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 TblLogUpdaterDao extends AbstractDbService{
    public List<SearchUpdateIntervalInfo> getLastUpdateIntervals(int number) throws InternalException {
        String q = "SELECT robot_date, updater_finish_date FROM tbl_log_updater ORDER BY robot_date DESC LIMIT ?";
        return getJdbcTemplate(WMCPartition.nullPartition()).query(q, getMapper(), number);
    }

    private ParameterizedRowMapper<SearchUpdateIntervalInfo> getMapper() {
        return new ParameterizedRowMapper<SearchUpdateIntervalInfo>() {
            @Override
            public SearchUpdateIntervalInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                Timestamp updateStartTime = rs.getTimestamp("robot_date");
                Timestamp updateFinishTime = rs.getTimestamp("updater_finish_date");

                DateTime startDateTime = new DateTime(updateStartTime.getTime());
                DateTime finishDateTime = null;
                if (updateFinishTime != null) {
                    finishDateTime = new DateTime(updateFinishTime.getTime());
                }
                return new SearchUpdateIntervalInfo(startDateTime, finishDateTime);
            }
        };
    }
}
