package ru.yandex.wmconsole.service.dao;

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

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import ru.yandex.common.util.collections.Pair;
import ru.yandex.wmconsole.data.HostInfoStatusEnum;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.service.AbstractDbService;
import ru.yandex.wmtools.common.util.SqlUtil;

/**
 * User: azakharov
 * Date: 30.10.13
 * Time: 11:30
 */
public class TblHostInfoDao extends AbstractDbService {
    public Pair<HostInfoStatusEnum, Date> getHostInfo(HostDbHostInfo hostDbHostInfo) throws InternalException {
        final String query = "SELECT status, status_date FROM tbl_host_info WHERE host_id = ?";
        List<Pair<HostInfoStatusEnum, Date>> res = getJdbcTemplate(new WMCPartition(hostDbHostInfo, null)).query(query,
                getMapper(), hostDbHostInfo.getHostDbHostId());
        return res.isEmpty() ? null : res.iterator().next();
    }

    public void addHostInfoOrUpdateStatus(HostDbHostInfo hostDbHostInfo, HostInfoStatusEnum status) throws
            InternalException
    {
        String q = "REPLACE INTO tbl_host_info (host_id, status, status_date) VALUES (?, ?, NOW())";
        getJdbcTemplate(new WMCPartition(hostDbHostInfo, null)).update(q,
                hostDbHostInfo.getHostDbHostId(), status.getValue());
    }

    private static ParameterizedRowMapper<Pair<HostInfoStatusEnum, Date>> getMapper() {
        return new ParameterizedRowMapper<Pair<HostInfoStatusEnum, Date>>() {

            @Override
            public Pair<HostInfoStatusEnum, Date> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Integer statusCode = SqlUtil.getIntNullable(rs, "status");
                HostInfoStatusEnum status = statusCode != null ? HostInfoStatusEnum.R.fromValueOrNull(statusCode) : null;
                Date statusDate = SqlUtil.safeGetTimestamp(rs, "status_date");
                return new Pair<HostInfoStatusEnum, Date>(status, statusDate);
            }
        };
    }
}
