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

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

class WriteOnce<V>(private val customMessage: String? = null) : ReadWriteProperty<Any?, V> {
	private var value: KOptional<V> = KOptional()

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

	override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
		this.value.ifPresent { throw IllegalStateException("Property ${property.name} is already initialized") }
		this.value = KOptional(value)
	}
}
