import { GameMode, EquipmentSlot, EntityComponentTypes } from "@minecraft/server";
import * as inventory_utils from "./inventory_utils";
import * as utils from "./utils";

const custom_tools = ['axehoe', 'axepick', 'axeshovel', 'pickhoe', 'pickshovel', 'shovelhoe', 'swordaxe', 'swordhoe', 'swordshovel', 'axe', 'hoe', 'shovel']
const materials = ['netherite', 'diamond', 'iron', 'copper', 'gold', 'stone', 'wood'];
const ignoreBlocks = ['table', 'door', 'furnace', 'chest', 'button', 'lever', 'frame', 'barrel', 'cake','command_block', 'repeater', 'beehive', 'cauldron'];
const igroneItems = ['fire', 'levitation', 'numbing', 'poisonous', 'weakening', 'withering'];

// Durability decrease when breaking blocks
export async function onPlayerBreakBlock(event) {
    let player = event.player;
    let typeId = event.itemStackAfterBreak.typeId.replace("tcs_cwp:", "");

    if(igroneItems.some(item => typeId.startsWith(item))) return

    if(inventory_utils.damageItem(player, EquipmentSlot.Mainhand, 2)) {
        player.runCommandAsync(`playsound random.break`);
    }

    // Particles
    let material = extractMaterial(typeId);     // tcs_cwp: is removed from typeId, crucial for function to work
    let blockLocation = event.block.location;
    try {
        utils.runEntityCommand(player, `particle tcs_cwp:${material}_tool ${blockLocation.x} ${blockLocation.y} ${blockLocation.z}`);
    } catch (error) {}
}

export async function onPlayerInteractWithBlock(event) {
    let player = event.player;
    let blockId = event.block.typeId;
    let typeId = event.itemStack.typeId.replace("tcs_cwp:", "");

    if(igroneItems.some(item => typeId.startsWith(item))) return

    if(inventory_utils.damageItem(player, EquipmentSlot.Mainhand, 2)) {
        player.runCommandAsync(`playsound random.break`);
    }

    let typeIdLastWord = typeId.split(/[_]/).pop(); // .split(/[_]/) - splits word whenever it encounters _. .pop() - gets only last word of those splited words.
    for(let i = 0; i<12; i++) {
        if(custom_tools[i] == typeIdLastWord) {
            player.startItemCooldown("tcs_cwp_animation_swing", 5.3);
            player.runCommandAsync(`playanimation @s animation.tcs_cwp.berserker_axe.slash.tp`);
            playToolSound(player, blockId, player.location);
            break;
        }
    }

    // Particles
    if(ignoreBlocks.some(block => blockId.endsWith(block))) return

    let material = extractMaterial(typeId);     // tcs_cwp: is removed from typeId, crucial for function to work
    let blockLocation = event.block.location;
    try {
        utils.runEntityCommand(player, `particle tcs_cwp:${material}_tool ${blockLocation.x} ${blockLocation.y} ${blockLocation.z}`);
    } catch (error) {}
}

// Chose sound based on block interacted with/time
function playToolSound(entity, blockId, location) {
    if(blockId.endsWith('wood') || blockId.endsWith('log')) {
        utils.playSound(entity, `@a[x=${location.x}, y=${location.y}, z=${location.z}, r=5]`, 'use.wood', 0.5, 1, 0.5);
        return;
    }
    if(blockId.endsWith('path')) {
        utils.playSound(entity, `@a[x=${location.x}, y=${location.y}, z=${location.z}, r=5]`, 'use.gravel', 0.5, 1, 0.5);
        return;
    }
    if(blockId.endsWith('farmland')) {
        utils.playSound(entity, `@a[x=${location.x}, y=${location.y}, z=${location.z}, r=5]`, 'use.gravel', 0.2, 0.85, 0);
        return;
    }
}

function extractMaterial(toolId) {
    let material = null;
    
    // Check if tooling starts with any material
    for (const mat of materials) {
        if (toolId.startsWith(mat)) {
            material = mat;
            break;
        }
    }
    
    // If no material found at start, check second word after first underscore
    if (material === null) {
        const stringParts = toolId.split('_');
        
        // Need at least 3 stringParts in string: something_material_something (double_copper_axe)
        if (stringParts.length >= 3) {
            const potentialMaterial = stringParts[1];
            if (materials.includes(potentialMaterial)) {
                material = potentialMaterial;
            }
        }
    }
    
    return material;
}

export async function onEntityHit(event) {
	const attacker = event.damagingEntity;

	if (!attacker || attacker.typeId !== "minecraft:player") return;

	const heldItem = attacker.getComponent("minecraft:equippable")?.getEquipment(EquipmentSlot.Mainhand);

	if (!heldItem) return;
    if(!heldItem.typeId.startsWith("tcs_cwp:")) return;
    let typeId = heldItem.typeId.replace("tcs_cwp:", "");
    if(igroneItems.some(item => typeId.startsWith(item))) return;
    let target = event.hitEntity;
    let typeFamily = target.getComponent(EntityComponentTypes.TypeFamily);
    if(typeFamily.hasTypeFamily('inanimate')) return

    let material = extractMaterial(typeId);     // tcs_cwp: is removed from typeId, crucial for function to work
    try {
        utils.runEntityCommand(attacker, `particle tcs_cwp:${material}_tool ${target.location.x} ${target.location.y} ${target.location.z}`);
    } catch (error) {}
}