package ru.dbotthepony.mc.otm.registry.game

import net.minecraft.client.color.block.BlockColor
import net.minecraft.client.color.item.ItemColor
import net.minecraft.client.renderer.BiomeColors
import net.minecraft.core.BlockPos
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.BlockAndTintGetter
import net.minecraft.world.level.block.state.BlockState
import net.neoforged.bus.api.IEventBus
import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent
import ru.dbotthepony.mc.otm.block.entity.decorative.HoloSignBlockEntity
import ru.dbotthepony.kommons.math.RGBAColor

object MBlockColors {
	private const val DEFAULT_WATER_TINT: Int = 0x3F76E4
	private const val DEFAULT_HOLO_SIGN_TINT: Int = 0xffe049

	private object CobblestoneGeneratorColor : BlockColor, ItemColor {
		override fun getColor(state: BlockState, light: BlockAndTintGetter?, pos: BlockPos?, index: Int): Int {
			return if (index == 0) {
				if (light == null || pos == null)
					DEFAULT_WATER_TINT
				else
					BiomeColors.getAverageWaterColor(light, pos)
			} else -1
		}

		override fun getColor(itemStack: ItemStack, index: Int): Int {
			return if (index == 0) DEFAULT_WATER_TINT else -1
		}
	}

	private object HoloSightColor : BlockColor, ItemColor {
		override fun getColor(state: BlockState, light: BlockAndTintGetter?, pos: BlockPos?, index: Int): Int {
			if (index != 0)
				return -1

			if (light == null || pos == null)
				return DEFAULT_HOLO_SIGN_TINT

			val blockEntity = light.getBlockEntity(pos) as? HoloSignBlockEntity ?: return DEFAULT_HOLO_SIGN_TINT
			return RGBAColor(blockEntity.textRed, blockEntity.textGreen, blockEntity.textBlue, blockEntity.textAlpha).toBGR()
		}

		override fun getColor(itemStack: ItemStack, index: Int): Int {
			return if (index == 0) DEFAULT_HOLO_SIGN_TINT else -1
		}
	}

	private fun registerBlockColors(event: RegisterColorHandlersEvent.Block) {
		for (it in MBlocks.COBBLESTONE_GENERATOR.values) {
			event.register(CobblestoneGeneratorColor, it)
		}

		event.register(HoloSightColor, MBlocks.HOLO_SIGN)
	}

	private fun registerItemColors(event: RegisterColorHandlersEvent.Item) {
		for (it in MBlocks.COBBLESTONE_GENERATOR.values) {
			event.register(CobblestoneGeneratorColor, it)
		}

		event.register(HoloSightColor, MBlocks.HOLO_SIGN)
	}

	fun register(bus: IEventBus) {
		bus.addListener(this::registerBlockColors)
		bus.addListener(this::registerItemColors)
	}
}
