package ru.yandex.wmconsole.service;

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

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 HostUnavailableService extends AbstractDbService {
    private static final String INSERT_HOST_UNAVAILABLE_QUERY =
            "INSERT INTO " +
                        "tbl_notification_hostunavailable (host_id, receive_time) " +
                    "VALUES (?, ?)";

    private static final String SELECT_HOST_UNAVAILABLE_QUERY =
            "SELECT " +
                        "host_id, receive_time " +
                    "FROM " +
                        "tbl_notification_hostunavailable " +
                    "WHERE " +
                        "hostunavailable_id = ?";

    private static final ParameterizedRowMapper<Long> HOST_UNAVAILABLE_MAPPER =
            new ParameterizedRowMapper<Long>() {
                private static final String FIELD_HOST_ID = "host_id";

                @Override
                public Long mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                    return resultSet.getLong(FIELD_HOST_ID);
                }
            };

    public Long addHostUnavailable(final Long hostId, final 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_HOST_UNAVAILABLE_QUERY,
                        Statement.RETURN_GENERATED_KEYS);
                ps.setLong(1, hostId);
                ps.setTimestamp(4, new Timestamp(date.getTime()));
                return ps;
            }
        };

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

    public Long getHostUnavailable(Long issueId) throws InternalException {
        return getJdbcTemplate(WMCPartition.nullPartition()).queryForObject(
                SELECT_HOST_UNAVAILABLE_QUERY,
                HOST_UNAVAILABLE_MAPPER,
                issueId
        );
    }
}
