package ru.yandex.wmconsole.service.dao;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import ru.yandex.wmconsole.data.HostInfoStatusEnum;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.data.info.HostStatusInfo;
import ru.yandex.wmconsole.data.info.PenaltyInfo;
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;

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

/**
 * User: azakharov
 * Date: 29.10.13
 * Time: 19:14
 */
public class TblPenaltyInfoDao extends AbstractDbService {

    public PenaltyInfo getPenaltyInfo(HostDbHostInfo hostDbHostInfo) throws InternalException {
        String query =
                "SELECT host_id, status_htarc, penalty_htarc, last_access_htarc, status_ya, penalty_ya, last_access_ya " +
                        "FROM tbl_penalty_info WHERE host_id = ?";

        ParameterizedRowMapper<PenaltyInfo> mapper = new ParameterizedRowMapper<PenaltyInfo>() {
            @Override
            public PenaltyInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                Integer statusHtarc = SqlUtil.getIntNullable(rs, "status_htarc");
                HostInfoStatusEnum statusHtarcEnum =
                        statusHtarc != null ? HostInfoStatusEnum.R.fromValueOrNull(statusHtarc) : null;
                Integer penaltyHtarc = SqlUtil.getIntNullable(rs, "penalty_htarc");
                Date lastAccessHtarc = SqlUtil.safeGetTimestamp(rs, "last_access_htarc");

                Integer statusYa = SqlUtil.getIntNullable(rs, "status_ya");
                HostInfoStatusEnum statusYaEnum =
                        statusYa != null ? HostInfoStatusEnum.R.fromValueOrNull(statusYa) : null;
                Integer penaltyYa = SqlUtil.getIntNullable(rs, "penalty_ya");
                Date lastAccessYa = SqlUtil.safeGetTimestamp(rs, "last_access_ya");
                return new PenaltyInfo(
                        new HostStatusInfo(statusHtarcEnum, statusYaEnum, null, penaltyHtarc, penaltyYa, true, true),
                        lastAccessHtarc,
                        lastAccessYa,
                        null);
            }
        };

        List<PenaltyInfo> res = getJdbcTemplate(new WMCPartition(hostDbHostInfo, null)).query(
                query, mapper, hostDbHostInfo.getHostDbHostId());
        return res.isEmpty() ? null : res.iterator().next();
    }
}
