package ru.yandex.wmconsole.service;

import java.sql.ResultSet;
import java.sql.SQLException;

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

import ru.yandex.wmconsole.data.SeverityEnum;
import ru.yandex.wmconsole.data.UserErrorOptions;
import ru.yandex.wmconsole.data.info.UrlErrorsWithCodeInfo;
import ru.yandex.wmtools.common.util.SqlUtil;

class GroupedUrlErrorWithTrendMapper implements ParameterizedRowMapper<UrlErrorsWithCodeInfo> {
    private static final String FIELD_ERROR_CODE = "error_code";
    private static final String FIELD_ERROR_COUNT = "error_count";
    private static final String FIELD_BANNED_COUNT = "banned_count";
    private static final String FIELD_ERROR_COUNT_TREND = "error_count_trend";

    private final UserErrorOptions userErrorOptions;

    public GroupedUrlErrorWithTrendMapper(UserErrorOptions userErrorOptions) {
        this.userErrorOptions = userErrorOptions;
    }

    @Override
    public UrlErrorsWithCodeInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
        int code = rs.getInt(FIELD_ERROR_CODE);
        int count = rs.getInt(FIELD_ERROR_COUNT);
        Integer bannedCount = SqlUtil.getIntNullable(rs, FIELD_BANNED_COUNT);
        if (bannedCount != null && bannedCount > 0) {
            count = count + bannedCount;
        }

        Integer errorCountTrend = SqlUtil.getIntNullable(rs, FIELD_ERROR_COUNT_TREND);
        SeverityEnum severity = userErrorOptions.getSeverityByCode(code);
        return new UrlErrorsWithCodeInfo(code, count, severity, errorCountTrend);
    }
}

