package nl.astraeus.nl.astraeus.persistence.reference import nl.astraeus.nl.astraeus.persistence.Persistable import nl.astraeus.nl.astraeus.persistence.currentTransaction import java.io.Serializable import kotlin.reflect.KProperty inline fun reference( initialValue:T ) = Reference(T::class.java, initialValue) inline fun nullableReference( initialValue:T? = null ) = NullableReference(T::class.java, initialValue) class Reference( val cls: Class, initialValue: S ) : Serializable { var id: Long = initialValue.id operator fun getValue(thisRef: Persistable, property: KProperty<*>): S { return currentTransaction()?.find(cls.kotlin, id) ?: throw IllegalStateException("Reference not found") } operator fun setValue(thisRef: Persistable, property: KProperty<*>, value: S) { currentTransaction()?.store(value) id = value.id } companion object { private const val serialVersionUID: Long = 1L } } class NullableReference( val cls: Class, initialValue: S? = null ) : Serializable { var id: Long? = initialValue?.id operator fun getValue(thisRef: Persistable, property: KProperty<*>): S? { return currentTransaction()?.find(cls.kotlin, id ?: 0L) } operator fun setValue(thisRef: Persistable, property: KProperty<*>, value: S?) { if (value != null) { // todo: only store if not already stored? currentTransaction()?.store(value) } id = value?.id } companion object { private const val serialVersionUID: Long = 1L } }