import { ItemStack, EnchantmentType   } from '@minecraft/server';
import * as game from "./game";

const reward = {
	"custom_item": { 
		weight: 10,
		items: [ "tcs_ohs:warriors_helmet", "tcs_ohs:warriors_chestplate", "tcs_ohs:warriors_leggings", "tcs_ohs:warriors_boots",
			"tcs_ohs:battle_axe", "tcs_ohs:battle_scythe", "tcs_ohs:inferno_bow", "tcs_ohs:venomous_sword", "tcs_ohs:wither_spear" ]
	},
	"combat": { 
		weight: 20,
		items: [ "chainmail_helmet", "chainmail_chestplate", "chainmail_leggings", "chainmail_boots",
			"iron_helmet", "iron_chestplate", "iron_leggings", "iron_boots",
			"golden_helmet", "golden_chestplate", "golden_leggings", "golden_boots",
			"iron_sword", "golden_sword", "trident", "crossbow", "bow", "arrow 10" ]
	},
	"tool": { 
		weight: 15,
		items: [ "iron_pickaxe", "golden_pickaxe", "iron_axe", "golden_axe", "diamond_axe", "iron_shovel", "golden_shovel", 
			"diamond_shovel", "iron_hoe", "golden_hoe", "diamond_hoe" ]
	},
	"food": { 
		weight: 25,
		items: [ "apple 4" , "golden_apple", "enchanted_golden_apple", "bread 2", "cooked_beef 2", "cooked_porkchop 2", 
			"cooked_chicken 2", "cooked_rabbit 2", "cooked_cod 3", "cooked_salmon 2", "baked_potato", "carrot 4",
			"golden_carrot", "beetroot 3", "beetroot_soup", "rabbit_stew", "mushroom_stew", "pumpkin_pie 2", "cake"  ]
	},
	"rare_item": { 
		weight: 5,
		items: [ "elytra", "totem_of_undying", "heart_of_the_sea", "ender_pearl", "dragon_egg" ]
	},
	"misc": { 
		weight: 15,
		items: [ "name_tag", "saddle", "firework_rocket", "lead", "filled_map", "compass", "clock", "music_disc"]
	},
	"potion": { 
		weight: 20,
		items: [ "healing 21", "regeneration 28", "strength 31", "swiftness 14", "night_vision 5", "water_breathing 19", 
			"fire_resistance 12", "weakness 34" ]
	},
	"enchant_book": { 
		weight: 10,
		items: [ "protection 3", "fire_protection 3", "feather_falling 3", "blast_protection 3", "projectile_protection 3",
			"respiration 3", "thorns 3", "depth_strider 3", "frost_walker 2", "soul_speed 2", "sharpness 4", "smite 4",
			"knockback 2", "unbreaking 3", "fortune 3", "fire_aspect 2", "looting 3", "power 4", "punch 2", "flame 1", "infinity 1",
			"efficiency 4", "silk_touch 1"
		]
	},
	"item": { 
		weight: 20,
		items: [ "lodestone", "experience_bottle", "axolotl_bucket", "blaze_powder 2", "ghast_tear", "sponge 2", "turtle_helmet 1", "conduit", 
			"phantom_membrane", "oak_log 8", "spruce_log 8", "obsidian 2", "nether_brick 8", "bee_nest", "bookshelf", "purple_shulker_box"]
	},
	"music_disc": { 
		weight: 10,
		items: [ "music_disc_13", "music_disc_cat", "music_disc_blocks", "music_disc_chirp", "music_disc_far", "music_disc_mall", 
			"music_disc_mellohi", "music_disc_stal", "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait", 
			"music_disc_pigstep", "music_disc_5", "music_disc_otherside", "music_disc_relic", "music_disc_precipice", 
			"music_disc_creator", "music_disc_creator_music_box" ]
	}
}

function selectReward(chest, slot, type, category)
{
	let item = category.items[Math.floor(Math.random() * category.items.length)];
	const chestContainer = chest.getComponent("minecraft:inventory").container;
	
	let count = 1;
	let dmg  = 0;
	if (type == "potion")
	{
		dmg = Number(item.split(" ")[1]);
		item = item.split(" ")[0];
		//game.debug(`replaceitem entity @s slot.inventory ${slot} potion 1 ${dmg}`);
		game.runMobCommand(chest, `replaceitem entity @s slot.inventory ${slot} potion 1 ${dmg}`);
		return;
	}
	if (type == "enchant_book")
	{
		try {
			let lvl = Number(item.split(" ")[1])-1;
			if (lvl > 0)
				lvl = Math.floor(Math.random() * lvl);
			lvl+=1;
			item = item.split(" ")[0];
			let book = new ItemStack("enchanted_book", 1);
			const enchantments = [{ level: lvl, type: new EnchantmentType(item)  }];
			book.getComponent("minecraft:enchantable").addEnchantments(enchantments);
			chestContainer.setItem(slot, book);
		}
		catch(error) {}
		return;
	}

	if (item.includes(" "))
	{
		count = Number(item.split(" ")[1]);
		item = item.split(" ")[0];
	}
	if (item === "music_disc")
	{
		category = reward["music_disc"];
		item = category.items[Math.floor(Math.random() * category.items.length)];
	}
	
	chestContainer.setItem(slot, new ItemStack(item, count));
}

function getWeightedRandomCategory(categories) {
    const totalWeight = categories.reduce((sum, cat) => sum + reward[cat].weight, 0);
    let random = Math.random() * totalWeight;
    
    for (const category of categories) {
        random -= reward[category].weight;
        if (random <= 0) {
            return category;
        }
    }
    return categories[categories.length - 1];
}

export async function createTreasure(chest) 
{
	//chest.nameTag = "Treasure chest";

	// Debug code to put all items of one category in all chests
	//let inventory = chest.getComponent("minecraft:inventory");
	//const chestCartContainer = inventory.container;
	//let cat_name = "enchant_book";
	//let category = reward[cat_name];
	//for (let slot=0; slot < category.length; slot++)
	//{
	//	selectReward(chest, slot, cat_name, reward[cat_name], slot);
	//}

	let remainingSlots = [ 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25 ];

	if (Math.floor(Math.random() >= 0.5))
		selectReward(chest, 13, "custom_item", reward["custom_item"]);
	
	let rewardCount = 2+Math.floor(Math.random()*3);
	//let remainingRewards = ["combat", "tool", "food", "rare_item", "misc", "potion", "enchant_book", "item"];
	let remainingRewards = ["combat", "tool", "food", "rare_item", "misc", "potion", "item"];
	
	for (let rewardInd=0; rewardInd<rewardCount; rewardInd++)
	{
		let slotInd = Math.floor(Math.random()*remainingSlots.length);
		let slot = remainingSlots[slotInd];
		remainingSlots.splice(slotInd, 1);

		let selectedCat = getWeightedRandomCategory(remainingRewards);
		remainingRewards = remainingRewards.filter(cat => cat !== selectedCat);

		selectReward(chest, slot, selectedCat, reward[selectedCat]);
	}
}
