package ru.dbotthepony.mc.otm.core.util

import ru.dbotthepony.kommons.util.Delegate
import ru.dbotthepony.kommons.util.KOptional
import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * Different from [Delegates.notNull] by allowing [V] to be nullable
 */
class NotNullVar<V> : Delegate<V>, ReadWriteProperty<Any?, V> {
	private var value: KOptional<V> = KOptional()

	override fun accept(t: V) {
		value = KOptional(t)
	}

	override fun get(): V {
		value.ifPresent { return it }
		throw IllegalStateException("Uninitialized variable")
	}

	override fun getValue(thisRef: Any?, property: KProperty<*>): V {
		value.ifPresent { return it }
		throw IllegalStateException("Uninitialized variable ${property.name}")
	}

	override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
		accept(value)
	}
}
