import * as mc from "@minecraft/server"
import { RETURN_ITEMS, TAGS } from "./sgs_cake_config";

//helper functions for interactive crafting stations

//check if a recipe in the station inventory is valid
export function checkRecipe(inventory, recipe_array) {
    let inventory_items = [];
    for (let index = 0; index < (inventory.size - inventory.emptySlotsCount); index++) {
        inventory_items.push(inventory.getItem(index));
    }

    //check recipes
    for (let index = 0; index < recipe_array.length; index++) {
        const recipe = recipe_array[index];

        let confirmedItems = [];
        //mc.world.sendMessage("§cRECIPE " + recipe.result[0]);

        for (let i = 0; i < recipe.ingredients.length; i++) {

            let confirmindex = 0;
            for (let j = 0; j < inventory_items.length; j++) {
                const ingredient = recipe.ingredients[i];
                const element = inventory_items[j];  //check against this element of inventory items

                //ingredient is TAG
                if (ingredient.tag != undefined) {
                    if (isTag(element, ingredient.tag) == true && !confirmedItems.includes(j)) {
                        confirmedItems.push(j);
                        //mc.world.sendMessage(i + " confirm TAG: " + element.typeId + " (" + j + ")");
                        break;
                    }
                }
                //ingredient is ID
                else {
                    if (ingredient == element.typeId && !confirmedItems.includes(j)) {
                        confirmedItems.push(j);
                        //mc.world.sendMessage(i + " confirm ID: " + element.typeId + " (" + j + ")");
                        break;
                    }
                }
            }
        }

        //once an identical amount of items has been confirmed, we have a match
        if (confirmedItems.length == recipe.ingredients.length) {
            return recipe;
        }



        /*
        recipe.ingredients.forEach(ingredient => {
            for (let index = 0; index < inventory_items.length; index++) {
                const element = inventory_items[index];
                //ingredient is a tag
                if (ingredient.tag != undefined) {
                    if (isTag(element, ingredient.tag) == true) {
                        confirmedItems.push(element)
                        break;
                    }
                }
                //ingredient is an id
                if (ingredient == element.typeId) {
                    confirmedItems.push(element)
                    break;
                }
            }
        });
        */
    };
}
function isTag(item, tag) {
    if (item.hasTag(tag)) return true;    //item has tag natively
    const itemdata = TAGS.find((f) => f.tag == tag);
    if (itemdata == undefined) return false;

    for (let index = 0; index < itemdata.items.length; index++) {
        const element = itemdata.items[index];
        if (item.typeId === element) {
            return true; //item is in virtual tag list
        }
    }
    return false;
}


//check if a recipe in the station inventory is valid
export function checkRecipeSimple(inventory, recipe_array) {
    let inventory_items = [];
    for (let index = 0; index < (inventory.size - inventory.emptySlotsCount); index++) {
        inventory_items.push(inventory.getItem(index).typeId);
    }

    //check recipes
    for (let index = 0; index < recipe_array.length; index++) {
        const recipe = recipe_array[index];

        let ingredients = [];
        recipe.ingredients.forEach(ingredient => {
            if (ingredient.tag != undefined) ingredients.push(ingredient.tag)
            else ingredients.push(ingredient)
        });


        if (JSON.stringify(inventory_items.sort()) === JSON.stringify(recipe.ingredients.sort())) {
            return recipe;
        }
    };
}

//returns empty container items like bottles or buckets that have been used in a recipe
export function returnContainterItems(player, recipe) {
    mc.system.runTimeout(() => {
        for (let index = 0; index < recipe.ingredients.length; index++) {
            const element = recipe.ingredients[index];

            const itemdata = RETURN_ITEMS.find((f) => f.id == element);
            if (itemdata != undefined) {
                const dropItem = new mc.ItemStack(itemdata.return_id, 1);
                const itemEntity = player.dimension.spawnItem(dropItem, player.location);
                itemEntity.clearVelocity();
            }
        }
        inventory.clearAll();
    }, 1)
}

//returns empty container items like bottles or buckets that have been used in a recipe
export function returnContainterItemsInventory(player, inventory) {
    mc.system.runTimeout(() => {
        for (let index = 0; index < inventory.size; index++) {

            const element = inventory.getItem(index).typeId;

            const itemdata = RETURN_ITEMS.find((f) => f.id == element);
            if (itemdata != undefined) {
                const dropItem = new mc.ItemStack(itemdata.return_id, 1);
                const itemEntity = player.dimension.spawnItem(dropItem, player.location);
                itemEntity.clearVelocity();
            }
        }
        inventory.clearAll();
    }, 1)
}

//returns items to the players if recipe is found invalid
export function returnItems(block, entity, inventory) {
    for (let index = 0; index < (inventory.size); index++) {
        const returnItem = inventory.getItem(index);
        inventory.setItem(index, undefined);
        if (returnItem != undefined) {
            const itemEntity = mc.world.getDimension(entity.dimension.id).spawnItem(returnItem, block.center());
            itemEntity.clearVelocity();
        }
    }
    entity.setProperty("sgs_cake:ingredients", 0);
}


export function clearDisplay(block) {
    const display_entities = getDisplayEntities(block);
    display_entities.forEach(ent => {
        const inventory = ent.getComponent('minecraft:inventory').container;

        for (let index = 0; index < (inventory.size); index++) {
            const returnItem = inventory.getItem(index);
            inventory.setItem(index, undefined);
            if (returnItem != undefined) {
                const itemEntity = mc.world.getDimension(block.dimension.id).spawnItem(returnItem, block.center());
                itemEntity.clearVelocity();
            }
        }

        ent.remove();
    });
}

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

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