package ru.yandex.wmconsole.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

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

import ru.yandex.wmconsole.data.UserErrorOptions;
import ru.yandex.wmconsole.data.info.ErrorUrlInfo;

class ErrorInfoMapper implements ParameterizedRowMapper<ErrorUrlInfo> {
    private static final String FIELD_ERROR_CODE = "error_code";
    private static final String FIELD_URL = "url";
    private static final String FIELD_INDEXED_ON = "indexed_on";
    private static final String FIELD_MODIFIED_ON = "modified_on";
    private static final String FIELD_HAS_INTERNAL_LINKS = "has_internal_links";
    private static final String FIELD_HAS_EXTERNAL_LINKS = "has_external_links";
    private static final String FIELD_SITEMAP_ID = "sitemap_id";

    private final UserErrorOptions userErrorOptions;

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

    @Override
    public ErrorUrlInfo mapRow(ResultSet rs, int i) throws SQLException {
        String url = rs.getString(FIELD_URL);
        Date indexedOn = new Date(TimeUnit.SECONDS.toMillis(rs.getInt(FIELD_INDEXED_ON)));
        if (rs.getInt(FIELD_INDEXED_ON) == 0) {
            indexedOn = null;
        }
        Date modTime = new Date(TimeUnit.SECONDS.toMillis(rs.getInt(FIELD_MODIFIED_ON)));
        if (rs.getInt(FIELD_MODIFIED_ON) == 0) {
            modTime = null;
        }
        int code = rs.getInt(FIELD_ERROR_CODE);
        boolean hasInternalLinks = (rs.getByte(FIELD_HAS_INTERNAL_LINKS) != 0);
        boolean hasExternalLinks = (rs.getByte(FIELD_HAS_EXTERNAL_LINKS) != 0);
        Long sitemapId = rs.getLong(FIELD_SITEMAP_ID);
        sitemapId = sitemapId == 0 ? null : sitemapId;
        return new ErrorUrlInfo(url, indexedOn, modTime, code, userErrorOptions.getSeverityByCode(code),
                hasInternalLinks, hasExternalLinks, sitemapId);
    }
}
