package ru.yandex.wmconsole.service;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;

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

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class SearchUpdateService extends AbstractDbService {
    private static final String INSERT_SEARCH_UPDATE_QUERY =
            "INSERT INTO " +
                        "tbl_notification_searchupdate (receive_time) " +
                    "VALUES (?)";

    private static final String SELECT_SEARCH_UPDATE_QUERY =
            "SELECT " +
                        "receive_time " +
                    "FROM " +
                        "tbl_notification_searchupdate " +
                    "WHERE " +
                        "searchupdate_id = ?";

    private static final ParameterizedRowMapper<Date> TIME_MAPPER =
            new ParameterizedRowMapper<Date>() {
                private static final String FIELD_RECEIVE_TIME = "receive_time";

                @Override
                public Date mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                    return resultSet.getDate(FIELD_RECEIVE_TIME);
                }
            };

    public Long addSearchUpdate(final java.util.Date date) throws InternalException {
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator psc = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(INSERT_SEARCH_UPDATE_QUERY,
                        Statement.RETURN_GENERATED_KEYS);
                ps.setTimestamp(1, new Timestamp(date.getTime()));
                return ps;
            }
        };

        getJdbcTemplate(WMCPartition.nullPartition()).getJdbcOperations().update(psc, generatedKeyHolder);
        return generatedKeyHolder.getKey().longValue();
    }

    public Date getSearchUpdateReceiveTime(Long searchUpdateId) throws InternalException {
        return getJdbcTemplate(WMCPartition.nullPartition()).queryForObject(
                SELECT_SEARCH_UPDATE_QUERY,
                TIME_MAPPER,
                searchUpdateId
        );
    }
}
