package ru.yandex.webmaster3.storage.util.sql.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import org.jetbrains.annotations.Nullable;
import org.springframework.jdbc.core.RowMapper;

import ru.yandex.webmaster3.storage.util.UUIDUtil;
import ru.yandex.wmtools.common.util.SqlUtil;

/**
 * @author avhaliullin
 */
public class SQLDataUtils extends SqlUtil {
    @Nullable
    public static UUID getUUID(ResultSet rs, String column) throws SQLException {
        byte[] res = column == null ? rs.getBytes(1) : rs.getBytes(column);
        if (rs.wasNull()) {
            return null;
        }
        return UUIDUtil.bytesToUUID(res);
    }

    public static byte[] convertUUID(UUID uuid) {
        if (uuid == null) {
            return null;
        }
        return UUIDUtil.uuidToBytes(uuid);
    }

    public static final RowMapper<UUID> UUID_MAPPER = createUUIDMapper(null);

    public static RowMapper<UUID> createUUIDMapper(final String columnName) {
        return new RowMapper<UUID>() {
            @Override
            public UUID mapRow(ResultSet rs, int rowNum) throws SQLException {
                return getUUID(rs, columnName);
            }
        };
    }
}
