package gaf3.core.jpa

import org.apache.commons.io.IOUtils
import java.io.ByteArrayOutputStream
import java.io.CharArrayWriter
import java.io.IOException
import java.sql.Blob
import java.sql.Clob
import java.sql.SQLException
import javax.sql.rowset.serial.SerialBlob
import javax.sql.rowset.serial.SerialException

object DataUtil {
    const val ZeroID: String = "00000000-0000-0000-0000-000000000000"

    fun <T> isNotEmpty(datas: List<T>?): Boolean {
        return datas != null && datas.isNotEmpty()
    }

    fun isNotEmpty(datas: ByteArray?): Boolean {
        return datas != null && datas.isNotEmpty()
    }

    @Deprecated("历史版本")
    fun clob2Str(data: Clob?): String? {
        if (data == null)
            return null
        try {
            val reader = data.characterStream
            val writer = CharArrayWriter()
            IOUtils.copy(reader, writer)
            return writer.toString()
        } catch (e: SQLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return null
    }

    @Deprecated("历史版本")
    fun blob2bytes(data: Blob?): ByteArray? {
        if (data == null)
            return null
        try {
            val `in` = data.binaryStream
            val out = ByteArrayOutputStream()
            IOUtils.copy(`in`, out)
            return out.toByteArray()
        } catch (e: SQLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return null
    }

    @Deprecated("历史版本")
    fun bytes2blob(data: ByteArray?): Blob? {
        if (data == null || data.isEmpty())
            return null
        try {
            return SerialBlob(data)
        } catch (e: SerialException) {
            e.printStackTrace()
        } catch (e: SQLException) {
            e.printStackTrace()
        }

        return null
    }

}
