package ru.dbotthepony.mc.otm.menu.tech

import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.item.ItemStack
import net.minecraftforge.common.ForgeHooks
import net.minecraftforge.common.capabilities.ForgeCapabilities
import ru.dbotthepony.mc.otm.block.entity.RedstoneSetting
import ru.dbotthepony.mc.otm.block.entity.tech.ChemicalGeneratorBlockEntity
import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.menu.MatteryMenu
import ru.dbotthepony.mc.otm.menu.MatterySlot
import ru.dbotthepony.mc.otm.menu.input.EnergyConfigPlayerInput
import ru.dbotthepony.mc.otm.menu.input.EnumInputWithFeedback
import ru.dbotthepony.mc.otm.menu.input.ItemConfigPlayerInput
import ru.dbotthepony.mc.otm.menu.widget.ProfiledLevelGaugeWidget
import ru.dbotthepony.mc.otm.menu.widget.ProgressGaugeWidget
import ru.dbotthepony.mc.otm.registry.MMenus

class ChemicalGeneratorMenu @JvmOverloads constructor(id: Int, inv: Inventory, tile: ChemicalGeneratorBlockEntity? = null)
	: MatteryMenu(MMenus.CHEMICAL_GENERATOR, id, inv, tile) {

	val redstoneConfig = EnumInputWithFeedback<RedstoneSetting>(this)
	val itemConfig = ItemConfigPlayerInput(this, tile?.itemConfig, allowPush = true)
	val energyConfig = EnergyConfigPlayerInput(this, tile?.energyConfig, allowPush = true)

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

	val fuelSlot = object : MatterySlot(tile?.fuelContainer ?: SimpleContainer(1), 0) {
		override fun mayPlace(itemStack: ItemStack): Boolean {
			return ForgeHooks.getBurnTime(itemStack, null) > 0
		}
	}

	val residueSlot = object : MatterySlot(tile?.residueContainer ?: SimpleContainer(1), 0) {
		override fun mayPlace(itemStack: ItemStack): Boolean {
			return false
		}
	}

	val batterySlot = object : MatterySlot(tile?.batteryContainer ?: SimpleContainer(1), 0) {
		override fun mayPlace(itemStack: ItemStack): Boolean {
			itemStack.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
				return it.canReceive()
			}

			return false
		}
	}

	val progress = ProgressGaugeWidget(this)
	val energy = ProfiledLevelGaugeWidget(this, tile?.energy)
	var burnTime by mSynchronizer.int().property

	init {
		addStorageSlot(fuelSlot)
		addStorageSlot(batterySlot)
		addStorageSlot(residueSlot)

		if (tile != null) {
			progress.with { if (tile.workTicksTotal == 0) 0f else 1f - tile.workTicks.toFloat() / tile.workTicksTotal }
		}
	}

	init {
		addInventorySlots()
	}

	override fun broadcastChanges() {
		super.broadcastChanges()
		burnTime = (tile as ChemicalGeneratorBlockEntity).workTicks
	}
}
