package ru.yandex.wmconsole.service.dao;

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

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

import ru.yandex.wmconsole.data.info.SearchUpdateNotificationInfo;
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 TblNotificationSearchupdate extends AbstractDbService {
    @Nullable
    public SearchUpdateNotificationInfo getLastSearchUpdateNotification() throws InternalException {
        String q = "SELECT searchupdate_id, receive_time FROM tbl_notification_searchupdate ORDER BY searchupdate_id DESC LIMIT 1";
        List<SearchUpdateNotificationInfo> result = getJdbcTemplate(WMCPartition.nullPartition()).query(q, getMapper());
        if (result.isEmpty()) {
            return null;
        }
        return result.get(0);
    }

    private static ParameterizedRowMapper<SearchUpdateNotificationInfo> getMapper() {
        return new ParameterizedRowMapper<SearchUpdateNotificationInfo>() {
            @Override
            public SearchUpdateNotificationInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                long searchupdateId = rs.getLong("searchupdate_id");
                Timestamp notificationTime = rs.getTimestamp("receive_time");

                return new SearchUpdateNotificationInfo(searchupdateId, new DateTime(notificationTime.getTime()));
            }
        };
    }
}
