package gay.pizza.CavesOfJolk

import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g3d.Attribute
import com.badlogic.gdx.graphics.g3d.Attributes
import com.badlogic.gdx.math.*
import ktx.math.div
import ktx.math.times
import ktx.math.unaryMinus
import org.hsluv.HUSLColorConverter
import kotlin.math.pow
import kotlin.random.Random

fun Float.axisDeadzone(min: Float, max: Float): Float
{
	val xabs = Math.abs(this)
	return if (xabs <= min) 0.0f
	else if (xabs >= max) Math.copySign(1.0f, this)
	else Math.copySign(xabs - min, this) / (max - min)
}

fun Vector2.cardinalDeadzone(min: Float, max: Float)
= Vector2(this.x.axisDeadzone(min, max), this.y.axisDeadzone(min, max))

fun Vector2.radialDeadzone(min: Float, max: Float): Vector2
{
	val magnitude = this.len()
	if (magnitude == 0.0f || magnitude < min)
		return Vector2()
	if (magnitude > max)
		return this / magnitude
	val rescale = (magnitude - min) / (max - min)
	return this / magnitude * rescale
}

val Double.saturate get() = if (this > 1.0) 1.0 else if (this < 0.0) 0.0 else this

class Util
{
	companion object
	{
		public fun colorFromAbgr8888(abgr8888: UInt) = Color(
			(abgr8888 and 0xFFu).toFloat() / 255.0f,
			((abgr8888 and 0xFF00u) shr 8).toFloat() / 255.0f,
			((abgr8888 and 0xFF0000u) shr 16).toFloat() / 255.0f,
			((abgr8888 and 0xFF000000u) shr 24).toFloat() / 255.0f)

		val zero get() = Vector3.Zero
		val one get() = Vector3(1.0f, 1.0f, 1.0f)
		val forward get() = -Vector3.Z
		val right get() = Vector3.X
		val up get() = Vector3.Y
	}
}

fun Color.lighten(ld: Double): Color
{
	val hsl = HUSLColorConverter.rgbToHsluv(doubleArrayOf(r.toDouble(), g.toDouble(), b.toDouble()))
	val gamma = 3.0
	hsl[2] = ((hsl[2] / 100.0).pow(1.0 / gamma) + ld * 0.8).saturate.pow(gamma) * 100.0
	val rgb = HUSLColorConverter.hsluvToRgb(hsl)
	return Color(rgb[0].toFloat(), rgb[1].toFloat(), rgb[2].toFloat(), a)
}

fun Color.mix(rhs: Color, x: Float) = Color(
	MathUtils.lerp(this.r, rhs.r, x),
	MathUtils.lerp(this.g, rhs.g, x),
	MathUtils.lerp(this.b, rhs.b, x),
	MathUtils.lerp(this.a, rhs.a, x))

//FIXME: find some way to get rid of these warnings
@Suppress("EXTENSION_SHADOWED_BY_MEMBER", "UNCHECKED_CAST")
fun <T: Attribute> Attributes.get(type: Long) = get(type) as? T

fun Random.nextFloat(min: Float, max: Float) = min + nextFloat() * (max - min)

fun RandomXS128.nextQuaternion(): Quaternion
{
	var x: Float
	var y: Float
	var z: Float
	do { x = nextFloat(-1.0f, 1.0f); y = nextFloat(-1.0f, 1.0f); z = x * x + y * y } while (z > 1.0f)
	var u: Float
	var v: Float
	var w: Float
	do { u = nextFloat(-1.0f, 1.0f); v = nextFloat(-1.0f, 1.0f); w = u * u + v * v } while (w > 1.0f)
	val s = kotlin.math.sqrt((1.0f - z) / w)
	return Quaternion(x, y, s * u, s * v)
}
