package ru.dbotthepony.mc.otm.datagen.loot

import net.minecraft.advancements.critereon.EnchantmentPredicate
import net.minecraft.advancements.critereon.ItemEnchantmentsPredicate
import net.minecraft.advancements.critereon.ItemPredicate
import net.minecraft.advancements.critereon.ItemSubPredicates
import net.minecraft.advancements.critereon.MinMaxBounds
import net.minecraft.util.valueproviders.UniformInt
import net.minecraft.world.item.enchantment.Enchantments
import net.minecraft.world.level.ItemLike
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.storage.loot.entries.AlternativesEntry
import net.minecraft.world.level.storage.loot.entries.LootItem
import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount
import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction
import net.minecraft.world.level.storage.loot.predicates.ExplosionCondition
import net.minecraft.world.level.storage.loot.predicates.MatchTool
import ru.dbotthepony.mc.otm.core.lookupOrThrow
import ru.dbotthepony.mc.otm.data.loot.Int2NumberProvider
import ru.dbotthepony.mc.otm.registry.game.MBlocks
import ru.dbotthepony.mc.otm.registry.game.MItems

private fun ore(lootTables: LootTables, ore: Block, clump: ItemLike, count: Int = 1) {
	lootTables.builder(ore) {
		add(AlternativesEntry.alternatives(
			LootItem.lootTableItem(ore).also {
				it.condition(MatchTool.toolMatches(
					ItemPredicate.Builder.item().withSubPredicate(
						ItemSubPredicates.ENCHANTMENTS,
						ItemEnchantmentsPredicate.enchantments(listOf(EnchantmentPredicate(
							lootTables.registry.get().lookupOrThrow(Enchantments.SILK_TOUCH), MinMaxBounds.Ints.atLeast(1)
						)))
					)
				))
			},

			LootItem.lootTableItem(clump).also {
				if (count != 1)
					it.apply(SetItemCountFunction.setCount(Int2NumberProvider(UniformInt.of(1, count))))

				it.apply(ApplyBonusCount.addOreBonusCount(lootTables.registry.get().lookupOrThrow(Enchantments.FORTUNE)))
				it.condition(ExplosionCondition.survivesExplosion())
			}
		))
	}
}

fun addLootTables(lootTables: LootTables) {
	lootTables.dropsSelf(MBlocks.MATTER_CABLE) { condition(ExplosionCondition.survivesExplosion()) }
	lootTables.dropsSelf(MBlocks.ENERGY_CABLES.values) { condition(ExplosionCondition.survivesExplosion()) }

	lootTables.dropsSelf(MBlocks.GRAVITATION_STABILIZER)
	lootTables.dropsOther(MBlocks.GRAVITATION_STABILIZER_LENS, MBlocks.GRAVITATION_STABILIZER)

	ore(lootTables, MBlocks.TRITANIUM_ORE, MItems.TRITANIUM_ORE_CLUMP)
	ore(lootTables, MBlocks.DEEPSLATE_TRITANIUM_ORE, MItems.TRITANIUM_ORE_CLUMP)

	ore(lootTables, MBlocks.DILITHIUM_ORE, MItems.DILITHIUM_CRYSTAL, 2)
	ore(lootTables, MBlocks.DEEPSLATE_DILITHIUM_ORE, MItems.DILITHIUM_CRYSTAL, 2)

}
