package ru.dbotthepony.mc.otm.block.entity.decorative

import net.minecraft.core.BlockPos
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.material.Fluids
import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
import ru.dbotthepony.mc.otm.block.entity.MatteryBlockEntity
import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.registry.MBlockEntities

class InfiniteWaterSourceBlockEntity(blockPos: BlockPos, blockState: BlockState) : MatteryBlockEntity(MBlockEntities.INFINITE_WATER_SOURCE, blockPos, blockState), IFluidHandler {
	override fun getTanks(): Int {
		return 1
	}

	override fun getFluidInTank(tank: Int): FluidStack {
		return FluidStack(Fluids.WATER, Int.MAX_VALUE)
	}

	override fun getTankCapacity(tank: Int): Int {
		return Int.MAX_VALUE
	}

	override fun isFluidValid(tank: Int, stack: FluidStack): Boolean {
		return false
	}

	override fun fill(resource: FluidStack, action: IFluidHandler.FluidAction): Int {
		return 0
	}

	override fun drain(resource: FluidStack, action: IFluidHandler.FluidAction): FluidStack {
		if (resource.fluid == Fluids.WATER || resource.fluid == Fluids.FLOWING_WATER) {
			return resource.copy()
		}

		return FluidStack.EMPTY
	}

	override fun drain(maxDrain: Int, action: IFluidHandler.FluidAction): FluidStack {
		return FluidStack(Fluids.WATER, maxDrain)
	}

	init {
		exposeGlobally(ForgeCapabilities.FLUID_HANDLER, this)

		for (side in sides.values) {
			val tracker = side.track(ForgeCapabilities.FLUID_HANDLER)

			val ticker = tickList.Ticker {
				tracker.get().ifPresentK {
					it.fill(FluidStack(Fluids.WATER, Int.MAX_VALUE), IFluidHandler.FluidAction.EXECUTE)
				}
			}

			tracker.addListener { ticker.isEnabled = it.isPresent }
		}
	}
}
