import * as mc from "@minecraft/server"
import * as config from './sgs_cake_config';

import "sgs_cake_guidebook.js";
import "./entities/sgs_cake_raccoon.js";
import "./entities/sgs_cake_van.js";

import { stoveManager } from "./blocks/sgs_cake_stove";
import { preptableManager } from "./blocks/sgs_cake_preptable";
import { foodEffectManager } from "./items/sgs_cake_foodEffect";
import { crafterManager } from "./blocks/sgs_cake_crafter";
import { multiblockManager } from "./blocks/sgs_cake_multiblock";

import { iceChurnManager } from "./crafting_stations/sgs_cake_ice_churn";
import { butterChurnManager } from "./crafting_stations/sgs_cake_butter_churn";
import { mixingBowlManager } from "./crafting_stations/sgs_cake_mixing_bowl";
import { cauldronManager } from "./crafting_stations/sgs_cake_cauldron";
import { blenderManager } from "./crafting_stations/sgs_cake_blender";
import { teaPotManager } from "./crafting_stations/sgs_cake_teapot";
import { PanManager } from "./crafting_stations/sgs_cake_pan";
import { MillstoneManager } from "./crafting_stations/sgs_cake_millstone";
import { FruitPressManager } from "./crafting_stations/sgs_cake_fruit_press";

import { treeManager } from "./crops/sgs_cake_treemanager";
import { cropManager } from "./crops/sgs_cake_cropmanager";
import { cakeSupportManager } from "./blocks/sgs_cake_cakesupport";
import { cakeBlockManager } from "./blocks/sgs_cake_cakeblock";
import { foodDisplayManager } from "./blocks/sgs_cake_fooddisplay";
import { awningSupportManager } from "./blocks/sgs_cake_awning";
import { variantManager } from "./blocks/sgs_cake_variant";
import { cinnamonManager } from "./crops/sgs_cake_cinnamon";
import { tradeStationManager } from "./blocks/sgs_cake_trade_station";
import { workbenchManager } from "./blocks/sgs_cake_workbench";
import { connectCardinalManager } from "./blocks/sgs_cake_connect_cardinal";
import { sittableManager } from "./blocks/sgs_cake_sittable";
import { umbrellaManager } from "./blocks/sgs_cake_umbrella";
import { miscBlocksManager } from "./blocks/sgs_cake_miscblocks";
import { cropBlocks, treeBlocks } from "./sgs_cake_crop_config";
import { glassRackManager } from "./blocks/sgs_cake_glassware";
import { waterBarrelManager } from "./blocks/sgs_cake_water_barrel";
import { bottleManager } from "./items/sgs_cake_bottle";
import { blockInventoryManager } from "./blocks/sgs_cake_blockinventory";
import { lightablemManager } from "./blocks/sgs_cake_lightable";


export const VERSION = "1.0.0";

const blockComponents = [
    {
        id: "sgs_cake:stove_top",
        code: {
            onPlace: (data) => {
                stoveManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                stoveManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:workbench",
        code: {
            onPlace: (data) => {
                workbenchManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                workbenchManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:workbench_top",
        code: {
            beforeOnPlayerPlace: (data) => {
                workbenchManager.beforeplaceTop(data)
            },
            onPlayerBreak: (data) => {
                workbenchManager.destroyTop(data)
            }
        }
    },
    {
        id: "sgs_cake:preptable_base",
        code: {
            onPlace: (data) => {
                preptableManager.onplaceBase(data)
            },
            onPlayerBreak: (data) => {
                preptableManager.destroyBase(data)
            }
        }
    },
    {
        id: "sgs_cake:preptable_top",
        code: {
            onPlace: (data) => {
                preptableManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                preptableManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:trade_station",
        code: {
            onPlace: (data) => {
                tradeStationManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                tradeStationManager.destroy(data)
            }
        }
    },
    /*
    {
        id: "sgs_cake:crafter",
        code: {
            beforeOnPlayerPlace: (data) => {
                crafterManager.beforeplace(data)
            }
        }
    },
    */
    {
        id: "sgs_cake:multiblock",
        code: {
            beforeOnPlayerPlace: (data) => {
                multiblockManager.beforeplace(data)
            },
            onPlayerBreak: (data) => {
                multiblockManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:icecream_churn",
        code: {
            onPlayerInteract: (data) => {
                iceChurnManager.interact(data)
            },
            onPlace: (data) => {
                iceChurnManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                iceChurnManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:butter_churn",
        code: {
            onPlayerInteract: (data) => {
                butterChurnManager.interact(data)
            },
            onPlace: (data) => {
                butterChurnManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                butterChurnManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:mixing_bowl",
        code: {
            onPlayerInteract: (data) => {
                mixingBowlManager.interact(data)
            },
            onPlace: (data) => {
                mixingBowlManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                mixingBowlManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:cauldron",
        code: {
            onPlayerInteract: (data) => {
                cauldronManager.interact(data)
            },
            onPlace: (data) => {
                cauldronManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                cauldronManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:blender",
        code: {
            onPlayerInteract: (data) => {
                blenderManager.interact(data)
            },
            onPlace: (data) => {
                blenderManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                blenderManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:teapot",
        code: {
            onPlayerInteract: (data) => {
                teaPotManager.interact(data)
            },
            onPlace: (data) => {
                teaPotManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                teaPotManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:pan",
        code: {
            onPlayerInteract: (data) => {
                PanManager.interact(data)
            },
            onPlace: (data) => {
                PanManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                PanManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:millstone",
        code: {
            onPlayerInteract: (data) => {
                MillstoneManager.interact(data)
            },
            onPlace: (data) => {
                MillstoneManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                MillstoneManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:fruit_press",
        code: {
            onPlayerInteract: (data, parameters) => {
                FruitPressManager.interact(data, parameters)
            },
            onPlace: (data, parameters) => {
                FruitPressManager.onplace(data, parameters)
            },
            onPlayerBreak: (data, parameters) => {
                FruitPressManager.destroy(data, parameters)
            }
        }
    },
    {
        id: "sgs_cake:crop",
        code: {
            beforeOnPlayerPlace: (data) => {
                cropManager.beforeplace(data)
            },
            onPlayerInteract: (data) => {
                cropManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                cropManager.tick(data.block);
            }
        }
    },
    {
        id: "sgs_cake:leaves",
        code: {
            beforeOnPlayerPlace: (data) => {
                treeManager.beforeplaceLeaves(data)
            },
            onPlayerBreak: (data) => {
                treeManager.destroyLeaves(data)
            },
            onPlayerInteract: (data) => {
                treeManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                treeManager.tick(data.block);
            }

        }
    },
    {
        id: "sgs_cake:log_cinnamon",
        code: {
            beforeOnPlayerPlace: (data) => {
                cinnamonManager.beforeplace(data)
            },
            onPlayerInteract: (data) => {
                cinnamonManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                cinnamonManager.tick(data.block);
            }
        }
    },
    {
        id: "sgs_cake:tree_sapling",
        code: {
            onPlayerInteract: (data) => {
                treeManager.interactSapling(data.block, data.player);
            },
            onRandomTick: (data) => {
                treeManager.tickSapling(data.block);
            }
        }
    },
    {
        id: "sgs_cake:cake_support",
        code: {
            beforeOnPlayerPlace: (data) => {
                cakeSupportManager.beforeplace(data)
            },
            onPlayerBreak: (data) => {
                cakeSupportManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake_custom:big_cake",
        code: {
            onPlayerInteract: (data) => {
                cakeBlockManager.interact(data)
            },
            beforeOnPlayerPlace: (data) => {
                cakeBlockManager.beforeplace(data)
            },
            /*
            onPlayerBreak: (data) => {
                cakeBlockManager.destroy(data)
            }
            */
        }
    },
    {
        id: "sgs_cake_custom:cake_sections",
        code: {
            onPlayerInteract: (data) => {
                cakeBlockManager.interactSections(data)
            }
        }
    },
    {
        id: "sgs_cake_custom:lit",
        code: {
            onPlayerInteract: (data) => {
                lightablemManager.interact(data)
            },
            onTick: (data) => {
                lightablemManager.tick(data)
            }
        }
    },
    {
        id: "sgs_cake:awning_support",
        code: {
            beforeOnPlayerPlace: (data) => {
                awningSupportManager.beforeplaceSupport(data)
            },
            onPlayerBreak: (data) => {
                awningSupportManager.destroySupport(data)
            }
        }
    },
    {
        id: "sgs_cake:awning",
        code: {
            beforeOnPlayerPlace: (data) => {
                awningSupportManager.beforeplace(data)
            }
        }
    },
    {
        id: "sgs_cake:flagstone",
        code: {
            beforeOnPlayerPlace: (data) => {
                variantManager.beforeplace(data)
            }
        }
    },
    {
        id: "sgs_cake:food_display",
        code: {
            onPlayerInteract: (data) => {
                foodDisplayManager.interact(data)
            },
            onPlayerBreak: (data) => {
                foodDisplayManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:food_display_stack",
        code: {
            onPlayerInteract: (data) => {
                foodDisplayManager.interactStack(data)
            },
            onPlayerBreak: (data) => {
                foodDisplayManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_cake:water_barrel",
        code: {
            onPlayerInteract: (data) => {
                waterBarrelManager.interact(data)
            }
        }
    },
    {
        id: "sgs_cake:milk_barrel",
        code: {
            onPlayerInteract: (data) => {
                waterBarrelManager.interactMilk(data)
            }
        }
    },
    {
        id: "sgs_cake_custom:connect_cardinal",
        code: {
            beforeOnPlayerPlace: (data, parameters) => {
                connectCardinalManager.beforeplace(data, parameters)
            },
            onPlayerBreak: (data, parameters) => {
                connectCardinalManager.destroy(data, parameters)
            }
        }
    },
    {
        id: "sgs_cake_custom:sittable",
        code: {
            onPlayerInteract: (data, parameters) => {
                sittableManager.interact(data, parameters)
            },
            onPlayerBreak: (data, parameters) => {
                sittableManager.destroy(data, parameters)
            }
        }
    },
    {
        id: "sgs_cake_custom:umbrella",
        code: {
            onPlace: (data, parameters) => {
                umbrellaManager.onplace(data, parameters)
            },
            onPlayerInteract: (data, parameters) => {
                umbrellaManager.interact(data, parameters)
            },
            onPlayerBreak: (data, parameters) => {
                umbrellaManager.destroy(data, parameters)
            }
        }
    },
    {
        id: "sgs_cake_custom:open_shelf",
        code: {
            onPlace: (data) => {
                miscBlocksManager.onplaceOpenShelf(data)
            }
        }
    },
    {
        id: "sgs_cake_custom:glassRack",
        code: {
            onPlayerInteract: (data, parameters) => {
                glassRackManager.interact(data, parameters)
            },
            onPlayerBreak: (data, parameters) => {
                glassRackManager.destroy(data, parameters)
            }
        }
    },
    {
        id: "sgs_cake:block_inventory",
        code: {
            onPlace: (data) => {
                blockInventoryManager.onplace(data)
            },
            onPlayerBreak: (data) => {
                blockInventoryManager.destroy(data)
            }
        }
    }
];

const itemComponents = [
    {
        id: "sgs_cake:bottle",
        code: {
            onUseOn: (data) => {
                bottleManager.onUseOn(data);
            }
        }
    }
    /*
    {
        id: "sgs_cake:food_effects",
        code: {
            onConsume: (data, parameters) => {
                foodEffectManager.onConsume(data, parameters)
            }
        }
    }
        */
]

initBlockComponents();
breakListener();
initAddOn();

function breakListener() {
    mc.world.beforeEvents.playerBreakBlock.subscribe((data) => {
        const { block, dimension, player, itemStack } = data;

        if (player.getGameMode() == mc.GameMode.creative) return;
        if (itemStack == undefined) return;
        const comp = itemStack.getComponent(mc.ItemEnchantableComponent.componentId);
        if (comp == undefined) return;
        if (!comp.hasEnchantment("silk_touch")) return;

        try {
            if (block.hasTag("sgs_cake_break_on_silktouch")) {
                data.cancel = true;
                mc.system.runTimeout(() => {
                    if (!(block.isValid())) return;
                    const loc = block.location;
                    block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air [] destroy`);
                });
                return;
            };

            const cropData = cropBlocks.find((f) => f.blockID == block.typeId);
            if (cropData != undefined) {
                data.cancel = true;
                mc.system.runTimeout(() => {
                    if (!(block.isValid())) return;
                    const loc = block.location;
                    block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air [] destroy`);
                });
                return;
            };

            const treeData = treeBlocks.find((f) => f.cropID == block.typeId);
            if (treeData != undefined) {
                data.cancel = true;
                mc.system.runTimeout(() => {
                    if (!(block.isValid())) return;
                    const loc = block.location;
                    block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air [] destroy`);
                });
                return;
            };
        } catch { }
    });
}

let reload = 0;
function initBlockComponents() {
    mc.system.beforeEvents.startup.subscribe((data) => {
        //reload trick to still have reload capability with this and other add-ons
        reload = reload + 1;
        if (reload > 1) return;

        //register custom crops
        for (const comp of blockComponents) {
            data.blockComponentRegistry.registerCustomComponent(comp.id, comp.code);
        }

        for (const comp of itemComponents) {
            data.itemComponentRegistry.registerCustomComponent(comp.id, comp.code);
        }
    });
}

function initAddOn() {
    mc.world.afterEvents.worldLoad.subscribe((data) => {
        if (mc.world.scoreboard.getObjective("sgs_cake_settings") === undefined) {
            mc.world.scoreboard.addObjective("sgs_cake_settings", "sgs_cake_settings");  //global settings
            mc.world.scoreboard.getObjective("sgs_cake_settings").setScore("RACCOON", 1);
            mc.world.scoreboard.getObjective("sgs_cake_settings").setScore("CRAFTSOUND", 1);
        }
    });
}

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

    if (id == "sgs_cake:refresh_display") {
        const block = mc.world.getDimension(sourceEntity.dimension.id).getBlock(sourceEntity.location);
        if (!block.hasTag("sgs_cake_display")) {
            try {
                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();
            } catch (error) {

            }
            sourceEntity.remove();
        }
        return;
    };

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

    if (id == "sgs_cake:refresh_seat") {
        const rideable = sourceEntity.getComponent('minecraft:rideable');
        if (rideable.getRiders()[0] == undefined) { //no longer a player sitting here
            sourceEntity.triggerEvent("sgs_cake:transform");
            return;
        }
        const block = mc.world.getDimension(sourceEntity.dimension.id).getBlock(sourceEntity.location);
        if (block.isAir) {  //some idiot broke the chair
            sourceEntity.triggerEvent("sgs_cake:transform");
            return;
        }
        return;
    };
})

//BLOCK INTERACT SOUNDS
mc.world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
    const block = data.block;

    mc.system.runTimeout(() => {
        if (block.typeId == "sgs_cake:oven_brick_mb") {
            block.dimension.playSound("block.campfire.crackle", block.location);
        }

        if (block.typeId == "sgs_cake:recipes") {
            if (block.permutation.getState("sgs_cake:can_craft") == 0) return;
            block.dimension.playSound("item.book.page_turn", block.location);
        }

        if (block.typeId == "sgs_cake:carpentry") {
            if (block.permutation.getState("sgs_cake:can_craft") == 0) return;
            block.dimension.playSound("item.book.page_turn", block.location);
        }
    }, 1)
    return;
});
