package ru.dbotthepony.kstarbound.world.terrain

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import ru.dbotthepony.kommons.math.linearInterpolation
import ru.dbotthepony.kstarbound.defs.world.TerrainSelectorParameters
import ru.dbotthepony.kstarbound.json.builder.JsonFactory

class MixTerrainSelector(data: Data, parameters: TerrainSelectorParameters) : AbstractTerrainSelector<MixTerrainSelector.Data>(data, parameters) {
	@JsonFactory
	data class Data(
		val mixSource: JsonElement,
		val mixSeedBias: Long = 0L,
		val aSource: JsonElement,
		val aSeedBias: Long = 0L,
		val bSource: JsonElement,
		val bSeedBias: Long = 0L,
	)

	private val mix = TerrainSelectorType.create(data.mixSource, parameters.withSeed(parameters.seed + data.mixSeedBias))
	private val aSource = TerrainSelectorType.create(data.aSource, parameters.withSeed(parameters.seed + data.aSeedBias))
	private val bSource = TerrainSelectorType.create(data.bSource, parameters.withSeed(parameters.seed + data.bSeedBias))

	override fun get(x: Int, y: Int): Double {
		val mix = mix[x, y]

		if (mix <= -1.0)
			return aSource[x, y]
		else if (mix >= 1.0)
			return bSource[x, y]
		else
			return linearInterpolation(mix * 0.5 + 0.5, aSource[x, y], bSource[x, y])
	}

	override val type: TerrainSelectorType
		get() = TerrainSelectorType.MIX
}
