import { Block, ItemStack, Player, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { addDamageItem } from "../../library/itemManager";
import { getGamemode } from "../../library/worldFuntions";

/**
 * Vista principal del sorter
 * @description Vista principal del sorter, donde se elige entre ordenar por addon tags o por nombres
 * @param {Player} player 
 * @param {ItemStack} itemStack 
 * @param {Block} block 
 */
export const chestSorterViewMain = (player, itemStack, block) => {
    const actionForm = new ActionFormData();
    actionForm.title("view.title.chest_sorter")//Chest Sorter
        .body("view.description.chest_sorter")//Select the type of sorting

    actionForm.button({ translate: "view.button_1.chest_sorter", with: [""] })//Sort for addon tags
    actionForm.button({ translate: "view.button_2.chest_sorter", with: [""] })//Sort for only names
    actionForm.button("view.button_3.chest_sorter");//Exit

    actionForm.show(player).then((data) => { 
        if (data.canceled) return;
        if (data.selection == 0) {
            chestSorterViewSortAddonTags(player, itemStack, block);
        } else if (data.selection == 1) {
            chestSorterViewSortNames(player, itemStack, block);
        } else {
            return;
        }
    })
}


/**
 * Vista de sorter para addon tags
 * @description Ordena los items por el tag de addon y nombre
 * @param {Player} player 
 * @param {ItemStack} itemStack 
 * @param {Block} block 
 */
const chestSorterViewSortAddonTags = (player, itemStack, block) => {
    const actionForm = new ActionFormData();
    actionForm.title("view.title.chest_sorter")
        .body({ translate: "view.button_1.chest_sorter", with: ["§r§9"]})
    
    actionForm.button("view.button_4.chest_sorter")//Descending
    actionForm.button("view.button_5.chest_sorter")//Acscending
    actionForm.button("view.button_6.chest_sorter");//Return

    actionForm.show(player).then((data) => { 
        if(data.canceled) return;
        if (data.selection == 0) {
            const container = block.getComponent('minecraft:inventory')?.container;

            if (container != undefined) {
                const slots = container.size;
                const items = [];
                for (let i = 0; i < slots; i++) {
                    const item = container.getItem(i);
                    if (item != undefined) {
                        items.push(item);
                    }
                }
                container.clearAll();
                items.sort((a, b) => {
                    if (a.typeId < b.typeId) return -1;
                    if (a.typeId > b.typeId) return 1;
                    return 0;
                });
                for (let i = 0; i < slots; i++) {
                    const item = items[i];
                    if (item != undefined) {
                        container.setItem(i, item);
                    }
                }
                let count = 0;
                const run = system.runInterval(() => {
                    player.runCommand(`playsound random.click @s ~ ~ ~ 0.3`);
                    count++;
                    if (count >= 4) {
                        system.clearRun(run);
                    }
                }, 2)
                if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                    addDamageItem(itemStack, player, 1);
                }
            }
        } else if (data.selection == 1) {
            const container = block.getComponent('minecraft:inventory')?.container;

            if (container != undefined) {
                const slots = container.size;
                const items = [];
                for (let i = 0; i < slots; i++) {
                    const item = container.getItem(i);
                    if (item != undefined) {
                        items.push(item);
                    }
                }
                container.clearAll();
                items.sort((a, b) => {
                    if (a.typeId > b.typeId) return -1;
                    if (a.typeId < b.typeId) return 1;
                    return 0;
                });
                for (let i = 0; i < slots; i++) {
                    const item = items[i];
                    if (item != undefined) {
                        container.setItem(i, item);
                    }
                }
                let count = 0;
                const run = system.runInterval(() => {
                    player.runCommand(`playsound random.click @s ~ ~ ~ 0.3`);
                    count++;
                    if (count >= 4) {
                        system.clearRun(run);
                    }
                }, 2)
                if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                    addDamageItem(itemStack, player, 1);
                }
            }
        } else {
            chestSorterViewMain(player, itemStack, block)
        }
    })
}


/**
 * Vista de sorter para nombres
 * @description Ordena los items por nombre, sin importar el tag de addon
 * @param {Player} player 
 * @param {ItemStack} itemStack 
 * @param {Block} block 
 */
const chestSorterViewSortNames = (player, itemStack, block) => {
    const actionForm = new ActionFormData();
    actionForm.title("view.title.chest_sorter")
        .body({ translate: "view.button_1.chest_sorter", with: ["§r§9"] })

    actionForm.button("view.button_4.chest_sorter")//Descending
    actionForm.button("view.button_5.chest_sorter")//Acscending
    actionForm.button("view.button_6.chest_sorter");//Return

    actionForm.show(player).then((data) => {
        if (data.canceled) return;
        if (data.selection == 0) {
            const container = block.getComponent('minecraft:inventory')?.container;

            if (container != undefined) {
                const slots = container.size;
                const items = [];
                for (let i = 0; i < slots; i++) {
                    const item = container.getItem(i);
                    if (item != undefined) {
                        items.push(item);
                    }
                }
                container.clearAll();
                items.sort((a, b) => {
                    if (a.typeId.split(":")[1] < b.typeId.split(":")[1]) return -1;
                    if (a.typeId.split(":")[1] > b.typeId.split(":")[1]) return 1;
                    return 0;
                });
                for (let i = 0; i < slots; i++) {
                    const item = items[i];
                    if (item != undefined) {
                        container.setItem(i, item);
                    }
                }
                let count = 0;
                const run = system.runInterval(() => {
                    player.runCommand(`playsound random.click @s ~ ~ ~ 0.3`);
                    count++;
                    if (count >= 4) {
                        system.clearRun(run);
                    }
                }, 2)
                if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                    addDamageItem(itemStack, player, 1);
                }
            }
        } else if (data.selection == 1) {
            const container = block.getComponent('minecraft:inventory')?.container;

            if (container != undefined) {
                const slots = container.size;
                const items = [];
                for (let i = 0; i < slots; i++) {
                    const item = container.getItem(i);
                    if (item != undefined) {
                        items.push(item);
                    }
                }
                container.clearAll();
                items.sort((a, b) => {
                    if (a.typeId.split(":")[1] > b.typeId.split(":")[1]) return -1;
                    if (a.typeId.split(":")[1] < b.typeId.split(":")[1]) return 1;
                    return 0;
                });
                for (let i = 0; i < slots; i++) {
                    const item = items[i];
                    if (item != undefined) {
                        container.setItem(i, item);
                    }
                }
                let count = 0;
                const run = system.runInterval(() => {
                    player.runCommand(`playsound random.click @s ~ ~ ~ 0.3`);
                    count++;
                    if (count >= 4) {
                        system.clearRun(run);
                    }
                }, 2)
                if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                    addDamageItem(itemStack, player, 1);
                }
            }
        } else {
            chestSorterViewMain(player, itemStack, block)
        }
    })
}