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

import net.minecraft.core.BlockPos
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.block.entity.MachineItemJob
import ru.dbotthepony.mc.otm.block.entity.JobContainer
import ru.dbotthepony.mc.otm.block.entity.JobStatus
import ru.dbotthepony.mc.otm.block.entity.MatteryWorkerBlockEntity
import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.container.HandlerFilter
import ru.dbotthepony.mc.otm.menu.tech.CobblerMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities

class CobblerBlockEntity(blockPos: BlockPos, blockState: BlockState)
	: MatteryWorkerBlockEntity<MachineItemJob>(MBlockEntities.COBBLESTONE_GENERATOR, blockPos, blockState, ::MachineItemJob) {
	override fun createMenu(containerID: Int, inventory: Inventory, ply: Player): AbstractContainerMenu {
		return CobblerMenu(containerID, inventory, this)
	}

	val container = MatteryContainer(this::itemContainerUpdated, CONTAINER_SIZE).also(::addDroppableContainer)

	val itemHandler = container.handler(object : HandlerFilter {
		override fun canInsert(slot: Int, stack: ItemStack): Boolean {
			return false
		}
	})

	val itemConfig = ConfigurableItemHandler(output = itemHandler)

	init {
		savetable(::container, INVENTORY_KEY)
	}

	override fun onJobFinish(job: MachineItemJob, id: Int): JobStatus {
		if (!container.fullyAddItem(job.itemStack)) {
			return JobStatus.FAILURE_ITEM
		}

		return JobStatus.SUCCESS
	}

	override fun computeNextJob(id: Int): JobContainer<MachineItemJob> {
		return JobContainer.success(MachineItemJob(ItemStack(Items.COBBLESTONE), 40.0))
	}

	companion object {
		const val CONTAINER_SIZE = 9
	}
}
