package cz.softdeluxe.jlib.hibernate

import org.hibernate.engine.spi.SessionImplementor
import org.hibernate.usertype.UserType
import java.io.Serializable
import java.sql.PreparedStatement
import java.sql.ResultSet

const val INT_ARRAY_TYPE = "cz.softdeluxe.jlib.hibernate.IntArrayUserType"
/**
 * podpora ukládní pole integerů pro hibernate
 *
 * @author balat
 */
@Suppress("unused")
class IntArrayUserType : UserType {

    override fun hashCode(x: Any?): Int = x?.hashCode() ?: 0

    override fun deepCopy(value: Any?): Any? = value

    override fun replace(original: Any?, target: Any?, owner: Any?): Any? = original

    override fun equals(x: Any?, y: Any?): Boolean = x == y

    override fun returnedClass(): Class<*> = IntArray::class.java

    override fun assemble(cached: Serializable?, owner: Any?): Any? = cached

    override fun disassemble(value: Any?): Serializable? = value as Serializable?

    override fun nullSafeSet(statement: PreparedStatement?, value: Any?, index: Int, session: SessionImplementor?) {
        val connection = statement?.connection

        val integers = value as Array<Int>
        val array = connection?.createArrayOf("integer", integers)

        statement?.setArray(index, array)
    }

    override fun nullSafeGet(rs: ResultSet, names: Array<out String>, session: SessionImplementor?, owner: Any?): Array<Int> {
        val array = rs.getArray(names[0])
        return array?.array as Array<Int>
    }

    override fun isMutable(): Boolean = false

    override fun sqlTypes(): IntArray = intArrayOf(java.sql.Types.ARRAY)
}