import * as mc from "@minecraft/server";
import { itemManager } from "../sgs_farm_lib";


mc.system.afterEvents.scriptEventReceive.subscribe((eventData) => {
    const { id, sourceEntity, message } = eventData;
    if (sourceEntity == null) return;

    if (id == "sgs_farm:refresh_display") {
        const block = mc.world.getDimension(sourceEntity.dimension.id).getBlock(sourceEntity.location);
        if(!block.hasTag("sgs_farm_display"))
        {
            const inventory = sourceEntity.getComponent('minecraft:inventory').container;
            const returnItem = inventory.getItem(0);
            const itemEntity = mc.world.getDimension(sourceEntity.dimension.id).spawnItem(returnItem, sourceEntity.location);
            itemEntity.clearVelocity();
            sourceEntity.remove();
        }
        return;
    };

    if (id == "sgs_farm:refresh_block") {
        const block = mc.world.getDimension(sourceEntity.dimension.id).getBlock(sourceEntity.location);
        if(!block.hasTag("sgs_farm_blockentity"))
        {
            sourceEntity.triggerEvent("sgs_farm:transform");
        }
        return;
    };
})

export class foodDisplayManager {
    static interact(data) {
        const block = data.block;
        const player = data.player;
        const location = block.center();

        const display_entity = getDisplayEntity(block);

        if (display_entity == undefined) {
            const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
            const heldItem = mainhand.getItem();
            if (heldItem == undefined) return;
            if (!heldItem.hasTag("is_food") && !heldItem.hasTag("is_fish")) return;    //only display items tagged food

            player.dimension.playSound("block.decorated_pot.insert", location);

            const display_entity = mc.world.getDimension(player.dimension.id).spawnEntity("sgs_farm:display", location);
            const direction = data.block.permutation.getState("minecraft:cardinal_direction");
            switch (direction) {
                case "north":
                    display_entity.setProperty("sgs_farm:rotation", 0);
                    break;
                case "east":
                    display_entity.setProperty("sgs_farm:rotation", 1);
                    break;
                case "south":
                    display_entity.setProperty("sgs_farm:rotation", 2);
                    break;
                case "west":
                    display_entity.setProperty("sgs_farm:rotation", 3);
                    break;
                default:
                    break;
            }

            if (block.typeId == "sgs_farm:display_stand") display_entity.setProperty("sgs_farm:animation", 1);
            if (block.typeId == "sgs_farm:display_plate") display_entity.setProperty("sgs_farm:animation", 2);
            if (block.typeId == "sgs_farm:display_jar") display_entity.setProperty("sgs_farm:animation", 2);

            //store item in display inventory
            const inventory = display_entity.getComponent('minecraft:inventory').container;
            const addItem = heldItem.clone();
            addItem.amount = 1;
            inventory.addItem(addItem);

            //place item visual
            mc.world.getDimension(player.dimension.id).runCommandAsync("/execute positioned " + location.x + " " + location.y + " " + location.z + " run /replaceitem entity @e[type=sgs_farm:display,r=0.2]  slot.weapon.mainhand 1 " + heldItem.typeId);

            if (player.getGameMode() == mc.GameMode.creative) return;
            mainhand.setItem(itemManager.reduceAmount(heldItem, 1));
            return;
        }
        else {
            clearDisplay(block);
        }
    }

    static interactStack(data) {
        const block = data.block;
        const player = data.player;
        const location = block.center();

        let max_stack = 1;
        if (block.typeId == "sgs_farm:display_jar") max_stack = 4;  //count starts at 0, obviously
        if (block.typeId == "sgs_farm:display_stand") max_stack = 2;

        const display_entities = getDisplayEntities(block);
        const count = display_entities.length;

        //max stack
        if (count <= max_stack) {
            const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
            const heldItem = mainhand.getItem();
            if (heldItem == undefined) {
                clearDisplay(block);
                return;
            }
            if (!heldItem.hasTag("is_food")  && !heldItem.hasTag("is_fish")) return;    //only display items tagged food

            player.dimension.playSound("block.decorated_pot.insert", location);

            const display_entity = mc.world.getDimension(player.dimension.id).spawnEntity("sgs_farm:display", location);
            const direction = data.block.permutation.getState("minecraft:cardinal_direction");

            if (direction == "north") display_entity.setProperty("sgs_farm:rotation", 0);
            if (direction == "east") display_entity.setProperty("sgs_farm:rotation", 1);
            if (direction == "south") display_entity.setProperty("sgs_farm:rotation", 2);
            if (direction == "west") display_entity.setProperty("sgs_farm:rotation", 3);

            if (block.typeId == "sgs_farm:display_stand") display_entity.setProperty("sgs_farm:animation", 1);
            if (block.typeId == "sgs_farm:display_plate") display_entity.setProperty("sgs_farm:animation", 2);
            if (block.typeId == "sgs_farm:display_jar") display_entity.setProperty("sgs_farm:animation", 2);
            //adjust height for this is a stack
            display_entity.setProperty("sgs_farm:level", count);

            if (count == 1) {
                display_entity.setProperty("sgs_farm:rand_x", 2);
                display_entity.setProperty("sgs_farm:rand_y", 3);
                display_entity.setProperty("sgs_farm:rand_z", 3);
            };
            if (count == 2) {
                display_entity.setProperty("sgs_farm:rand_x", 2);
                display_entity.setProperty("sgs_farm:rand_y", -3);
                display_entity.setProperty("sgs_farm:rand_z", -2);
            };
            if (count == 3) {
                display_entity.setProperty("sgs_farm:rand_x", -2);
                display_entity.setProperty("sgs_farm:rand_y", 2);
                display_entity.setProperty("sgs_farm:rand_z", 3);
            };
            if (count == 4) {
                display_entity.setProperty("sgs_farm:rand_x", 3);
                display_entity.setProperty("sgs_farm:rand_y", -2);
                display_entity.setProperty("sgs_farm:rand_z", 1);
            }

            //store item in display inventory
            const inventory = display_entity.getComponent('minecraft:inventory').container;
            const addItem = heldItem.clone();
            addItem.amount = 1;
            inventory.addItem(addItem);

            //place item visual
            mc.world.getDimension(player.dimension.id).runCommandAsync("/execute positioned " + location.x + " " + location.y + " " + location.z + " run /replaceitem entity @e[type=sgs_farm:display,r=0.2,tag=!sgs_farm_assigned]  slot.weapon.mainhand 1 " + heldItem.typeId);
            mc.system.runTimeout(() => { display_entity.addTag("sgs_farm_assigned") }, 1);    //add tag

            if (player.getGameMode() == mc.GameMode.creative) return;
            mainhand.setItem(itemManager.reduceAmount(heldItem, 1));
            return;
        }
        else {
            clearDisplay(block);
        }
    }

    static destroy(data) {
        const block = data.block;
        const player = data.player;
        const location = block.center();

        const display_entities = getDisplayEntities(block);
        display_entities.forEach(ent => {
            const inventory = ent.getComponent('minecraft:inventory').container;
            let returnItem = inventory.getItem(0);
            const itemEntity = mc.world.getDimension(player.dimension.id).spawnItem(returnItem, location);
            itemEntity.clearVelocity();
            ent.remove();
        });

    }
}

function clearDisplay(block) {

    const display_entities = getDisplayEntities(block);
    display_entities.forEach(ent => {
        const inventory = ent.getComponent('minecraft:inventory').container;
        const returnItem = inventory.getItem(0);
        const itemEntity = mc.world.getDimension(block.dimension.id).spawnItem(returnItem, block.center());
        itemEntity.clearVelocity();
        ent.remove();
    });
}

export function getDisplayEntity(block) {
    const location = block.center();
    return mc.world.getDimension(block.dimension.id).getEntities({ location, families: ["sgs_farm_display"], maxDistance: 0.2 })[0];
}

export function getDisplayEntities(block) {
    const location = block.center();
    return mc.world.getDimension(block.dimension.id).getEntities({ location, families: ["sgs_farm_display"], maxDistance: 0.2 });
}