package ru.yandex.wmconsole.service;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import ru.yandex.common.util.collections.Cu;
import ru.yandex.misc.db.q.InsertSqlQueryBuilder;
import ru.yandex.misc.db.q.SqlQuery;
import ru.yandex.wmconsole.data.ClearBadSoftwareNotificationInfo;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.service.AbstractDbService;

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

/**
 * User: azakharov
 * Date: 08.08.14
 * Time: 15:22
 */
public class ClearBadSoftwareNotificationService extends AbstractDbService {

    public Long saveNotificationInfo(Long hostId, Date receiveTime) throws InternalException {
        SqlQuery query = new InsertSqlQueryBuilder().tableName("tbl_notification_clear_bad_software")
                .columnValue("host_id", hostId)
                .columnValue("receive_time", receiveTime)
                .toSqlQuery();
        Number res = getJdbcTemplate(WMCPartition.nullPartition()).insertSingle(query.sql(), query.args());
        return res.longValue();
    }

    public ClearBadSoftwareNotificationInfo getSingleNotificationInfo(Long issueId) throws InternalException {
        final String query = "SELECT host_id, receive_time FROM tbl_notification_clear_bad_software WHERE issue_id = ?";
        ParameterizedRowMapper<ClearBadSoftwareNotificationInfo> m = new ParameterizedRowMapper<ClearBadSoftwareNotificationInfo>() {
            @Override
            public ClearBadSoftwareNotificationInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new ClearBadSoftwareNotificationInfo(rs.getLong("host_id"), rs.getTimestamp("receive_time"));
            }
        };
        List<ClearBadSoftwareNotificationInfo> res = getJdbcTemplate(WMCPartition.nullPartition()).query(query, m, issueId);
        return res.isEmpty() ? null : Cu.first(res);
    }
}
