package ru.dbotthepony.mc.otm.menu.decorative

import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.item.ItemStack
import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.fluids.capability.IFluidHandler
import ru.dbotthepony.mc.otm.block.entity.RedstoneSetting
import ru.dbotthepony.mc.otm.block.entity.decorative.FluidTankBlockEntity
import ru.dbotthepony.mc.otm.capability.isNotEmpty
import ru.dbotthepony.mc.otm.capability.isNotFull
import ru.dbotthepony.mc.otm.menu.MachineOutputSlot
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.menu.MatterySlot
import ru.dbotthepony.mc.otm.menu.input.EnumInputWithFeedback
import ru.dbotthepony.mc.otm.menu.input.FluidConfigPlayerInput
import ru.dbotthepony.mc.otm.menu.input.ItemConfigPlayerInput
import ru.dbotthepony.mc.otm.menu.widget.FluidGaugeWidget
import ru.dbotthepony.mc.otm.registry.MMenus

class FluidTankMenu(containerId: Int, inventory: Inventory, tile: FluidTankBlockEntity? = null) : MatteryMenu(MMenus.FLUID_TANK, containerId, inventory, tile) {
	val fluid = FluidGaugeWidget(mSynchronizer, tile?.fluid)
	val equipment = makeEquipmentSlots(true)
	val itemConfig = ItemConfigPlayerInput(this, tile?.itemConfig)
	val redstoneConfig = EnumInputWithFeedback<RedstoneSetting>(this)
	val fluidConfig = FluidConfigPlayerInput(this, tile?.fluidConfig)

	val drainInput = object : MatterySlot(tile?.drainInput ?: SimpleContainer(1), 0) {
		override fun mayPlace(itemStack: ItemStack): Boolean {
			return super.mayPlace(itemStack) &&
				itemStack
				.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM)
				.map { it.isNotEmpty }
				.orElse(false)
		}
	}

	val fillInput = object : MatterySlot(tile?.fillInput ?: SimpleContainer(1), 0) {
		override fun mayPlace(itemStack: ItemStack): Boolean {
			return super.mayPlace(itemStack) &&
				(if (itemStack.count <= 1) itemStack else itemStack.copyWithCount(1))
				.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM)
				.map {
					if (fluid.fluid.isEmpty)
						it.tanks > 0
					else
						it.fill(fluid.fluid, IFluidHandler.FluidAction.SIMULATE) > 0
				}
				.orElse(false)
		}
	}

	val output = MachineOutputSlot(tile?.output ?: SimpleContainer(1), 0)

	init {
		// сначала слот на заполнение из бака
		addStorageSlot(fillInput)
		addStorageSlot(drainInput)
		addStorageSlot(output)
		addInventorySlots()

		if (tile != null) {
			redstoneConfig.with(tile.redstoneControl::redstoneSetting)
		}
	}
}
