package org.mte.numecoeval.common.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ResultSetUtils {

    private ResultSetUtils() {
        // Nothing to do
    }

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static LocalDate getLocalDate(ResultSet resultSet, String columnName) throws SQLException {
        if (checkColumnInResultSet(resultSet, columnName)) return null;

        return resultSet.getDate(columnName).toLocalDate();
    }

    public static LocalDateTime getLocalDateTime(ResultSet resultSet, String columnName) throws SQLException {
        if (checkColumnInResultSet(resultSet, columnName)) return null;

        return resultSet.getTimestamp(columnName).toLocalDateTime();
    }

    public static Integer getInteger(ResultSet resultSet, String columnName) throws SQLException {
        if (checkColumnInResultSet(resultSet, columnName)) return null;

        return resultSet.getInt(columnName);
    }

    public static Float getFloat(ResultSet resultSet, String columnName) throws SQLException {
        if (checkColumnInResultSet(resultSet, columnName)) return null;

        return resultSet.getFloat(columnName);
    }

    public static Double getDouble(ResultSet resultSet, String columnName) throws SQLException {
        if (checkColumnInResultSet(resultSet, columnName)) return null;

        return resultSet.getDouble(columnName);
    }

    private static boolean checkColumnInResultSet(ResultSet resultSet, String columnName) throws SQLException {
        if (resultSet == null || "".equals(columnName)) {
            return true;
        }

        var value = resultSet.getString(columnName);
        return value == null || "".equals(value);
    }
}
