import * as mc from "@minecraft/server"
import { cropBlocks, cropsCombined, treeBlocks } from './crops/sgs_farm_cropconfig';
import { cropManager } from "./crops/sgs_farm_cropmanager";
import { frameManager } from "./crops/sgs_farm_framemanager";
import { vineManager } from "./crops/sgs_farm_vinemanager";
import { workbenchManager } from "./blocks/sgs_farm_workbench";
import { flowerManager } from "./decoration/sgs_farm_flowermanager";
import { fenceManager } from "./decoration/sgs_farm_fencemanager";
import { treeManager } from "./crops/sgs_farm_treemanager";

import "machines/sgs_farm_tractor.js";
import "items/sgs_farm_watering_can.js";
import "items/sgs_farm_hat.js";
import "sgs_farm_guidebook.js";
import "u1/sgs_farm_irrigate.js";
import "u3/sgs_farm_animalconfig";

import { stoveManager } from "./blocks/sgs_farm_stove";
import { preptableManager } from "./blocks/sgs_farm_preptable";
import { crafterManager } from "./blocks/sgs_farm_crafter";
import { seedhandlerManager } from "./blocks/sgs_farm_seedhandler";
import { sprinklerManager } from "./blocks/sgs_farm_sprinkler";
import { windowManager } from "./decoration/sgs_farm_window";
import { planterManager } from "./blocks/sgs_farm_planter";
import { herbPotManager } from "./blocks/sgs_farm_herbpot";
import { multiblockManager } from "./blocks/sgs_farm_multiblock";
import { variantManager } from "./blocks/sgs_farm_variant";
import { wateringCanManager } from "./items/sgs_farm_watering_can";
import { glassRackManager } from "./decoration/sgs_farm_glassware";
import { sickleManager } from "./items/sgs_farm_sickle";
import { foodDisplayManager } from "./blocks/sgs_farm_fooddisplay";
import { stepManager } from "./blocks/sgs_farm_step";
import { stackfenceManager } from "./u3/sgs_farm_stackfencemanager";
import { feederManager } from "./u3/sgs_farm_feeder";
import { connectCardinalManager } from "./u3/sgs_farm_connectCardinal";
import { coopManager } from "./u3/sgs_farm_coop";
import { trapdoorManager } from "./u3/sgs_farm_trapdoor";
import { fishTrapManager } from "./u3/sgs_farm_fish_trap";


export const VERSION = "1.3.2";

const blockComponents = [
    {
        id: "sgs_farm:crop",
        code: {
            beforeOnPlayerPlace: (data) => {
                cropManager.beforeplace(data)
            },
            onPlayerInteract: (data) => {
                cropManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                cropManager.tick(data.block);
            }
        }
    },
    {
        id: "sgs_farm:a_frame_crop",
        code: {
            onPlayerDestroy: (data) => {
                cropManager.destroyAFrame(data.block, data.destroyedBlockPermutation);
            }
        }
    },
    {
        id: "sgs_farm:p_frame_crop",
        code: {
            onPlayerDestroy: (data) => {
                cropManager.destroyPFrame(data.block, data.destroyedBlockPermutation);
            }
        }
    },
    {
        id: "sgs_farm:frame",
        code: {
            onPlayerInteract: (data) => {
                frameManager.interact(data.block, data.player);
            }
        }
    },
    {
        id: "sgs_farm:vine_frame_crop",
        code: {
            onRandomTick: (data) => {
                vineManager.tick(data.block);
            },
            onPlayerInteract: (data) => {
                vineManager.interactCrop(data.block, data.player);
            }
        }
    },
    {
        id: "sgs_farm:vine_frame",
        code: {
            beforeOnPlayerPlace: (data) => {
                vineManager.beforeplaceFrame(data)
            },
            onPlayerInteract: (data) => {
                vineManager.interactFrame(data);
            },
            onPlayerDestroy: (data) => {
                vineManager.destroyFrame(data);
            }
        }
    },
    {
        id: "sgs_farm:meadowflower",
        code: {
            onPlayerInteract: (data) => {
                flowerManager.interact(data.block, data.player);
            },
            onPlayerDestroy: (data) => {
                flowerManager.destroy(data);
            }
        }
    },
    {
        id: "sgs_farm:meadowbush",
        code: {
            onPlayerInteract: (data) => {
                flowerManager.interactFlowerBush(data.block, data.player);
            }
        }
    },
    {
        id: "sgs_farm:flower_starter",
        code: {
            beforeOnPlayerPlace: (data) => {
                flowerManager.beforeplace(data);
            }
        }
    },
    {
        id: "sgs_farm:fence",
        code: {
            beforeOnPlayerPlace: (data) => {
                fenceManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                fenceManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:fence_gate",
        code: {
            beforeOnPlayerPlace: (data) => {
                fenceManager.beforeplaceGate(data)
            },
            onPlayerInteract: (data) => {
                fenceManager.interactGate(data.block, data.player);
            },
            onPlayerDestroy: (data) => {
                fenceManager.destroyGate(data)
            }
        }
    },
    {
        id: "sgs_farm:leaves",
        code: {
            beforeOnPlayerPlace: (data) => {
                treeManager.beforeplaceLeaves(data)
            },
            onPlayerDestroy: (data) => {
                treeManager.destroyLeaves(data)
            },
            onPlayerInteract: (data) => {
                treeManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                treeManager.tick(data.block);
            }
        }
    },
    {
        id: "sgs_farm:tree_sapling",
        code: {
            onPlayerInteract: (data) => {
                treeManager.interactSapling(data.block, data.player);
            },
            onRandomTick: (data) => {
                treeManager.tickSapling(data.block);
            }
        }
    },
    {
        id: "sgs_farm:stove_top",
        code: {
            beforeOnPlayerPlace: (data) => {
                stoveManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                stoveManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:preptable_top",
        code: {
            beforeOnPlayerPlace: (data) => {
                preptableManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                preptableManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:workbench",
        code: {
            beforeOnPlayerPlace: (data) => {
                workbenchManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                workbenchManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:workbench_top",
        code: {
            beforeOnPlayerPlace: (data) => {
                workbenchManager.beforeplaceTop(data)
            },
            onPlayerDestroy: (data) => {
                workbenchManager.destroyTop(data)
            }
        }
    },
    {
        id: "sgs_farm:crafter",
        code: {
            beforeOnPlayerPlace: (data) => {
                crafterManager.beforeplace(data)
            }
        }
    },
    {
        id: "sgs_farm:variant",
        code: {
            beforeOnPlayerPlace: (data) => {
                variantManager.beforeplace(data)
            }
        }
    },
    {
        id: "sgs_farm:seed_processor",
        code: {
            onPlayerInteract: (data) => {
                seedhandlerManager.interactProcessor(data)
            }
        }
    },
    {
        id: "sgs_farm:seed_recycler",
        code: {
            onPlayerInteract: (data) => {
                seedhandlerManager.interactRecycler(data)
            }
        }
    },
    {
        id: "sgs_farm:pipe",
        code: {
            beforeOnPlayerPlace: (data) => {
                sprinklerManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                sprinklerManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:pump",
        code: {
            beforeOnPlayerPlace: (data) => {
                sprinklerManager.beforeplacePump(data)
            },
            onPlayerDestroy: (data) => {
                sprinklerManager.destroyPump(data)
            },
            onTick: (data) => {
                sprinklerManager.tickPump(data.block)
            }
        }
    },
    {
        id: "sgs_farm:sprinkler",
        code: {
            onTick: (data) => {
                sprinklerManager.tick(data.block)
            },
            onPlayerDestroy: (data) => {
                sprinklerManager.destroysprinkler(data)
            },
            onPlayerInteract: (data) => {
                sprinklerManager.interact(data.block)
            }
        }
    },
    {
        id: "sgs_farm:window_double",
        code: {
            beforeOnPlayerPlace: (data) => {
                windowManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                windowManager.destroy(data)
            },
            onPlace: (data) => {
                windowManager.placed(data)
            }
        }
    },
    /*
    {
        id: "sgs_farm:pergola",
        code: {
            beforeOnPlayerPlace: (data) => {
                pergolaManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                pergolaManager.destroy(data)
            }
        }
    },
    */
    {
        id: "sgs_farm:planter",
        code: {
            beforeOnPlayerPlace: (data) => {
                planterManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                planterManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:herbpot",
        code: {
            onPlayerInteract: (data) => {
                herbPotManager.interact(data.block, data.player);
            },
            onRandomTick: (data) => {
                herbPotManager.tick(data.block);
            },
            onPlayerDestroy: (data) => {
                herbPotManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:multiblock",
        code: {
            beforeOnPlayerPlace: (data) => {
                multiblockManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                multiblockManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:glass_rack",
        code: {
            onPlayerInteract: (data) => {
                glassRackManager.interact(data.block, data.player)
            },
            onPlayerDestroy: (data) => {
                glassRackManager.destroy(data)
            }
        }
    },
    //U2 Update
    {
        id: "sgs_farm:food_display",
        code: {
            onPlayerInteract: (data) => {
                foodDisplayManager.interact(data)
            },
            onPlayerDestroy: (data) => {
                foodDisplayManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:food_display_stack",
        code: {
            onPlayerInteract: (data) => {
                foodDisplayManager.interactStack(data)
            },
            onPlayerDestroy: (data) => {
                foodDisplayManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:step",
        code: {
            beforeOnPlayerPlace: (data) => {
                stepManager.beforeplace(data)
            }
        }
    },
    {
        id: "sgs_farm:step_support",
        code: {
            onPlayerDestroy: (data) => {
                stepManager.destroy(data)
            }
        }
    },
    //U3
    {
        id: "sgs_farm:stackfence",
        code: {
            beforeOnPlayerPlace: (data) => {
                stackfenceManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                stackfenceManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:stackfence_gate",
        code: {
            beforeOnPlayerPlace: (data) => {
                stackfenceManager.beforeplaceGate(data)
            },
            onPlayerInteract: (data) => {
                stackfenceManager.interactGate(data.block, data.player);
            },
            onPlayerDestroy: (data) => {
                stackfenceManager.destroyGate(data)
            }
        }
    },
    {
        id: "sgs_farm:feeder",
        code: {
            beforeOnPlayerPlace: (data) => {
                feederManager.beforeplace(data)
            },
            onPlayerInteract: (data) => {
                feederManager.interact(data);
            },
            onPlayerDestroy: (data) => {
                feederManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:feeder_rabbit",
        code: {
            beforeOnPlayerPlace: (data) => {
                feederManager.beforeplace_cardinal(data)
            },
            onPlayerInteract: (data) => {
                feederManager.interact(data);
            },
            onPlayerDestroy: (data) => {
                feederManager.destroy_cardinal(data)
            }
        }
    },
    {
        id: "sgs_farm:coop",
        code: {
            beforeOnPlayerPlace: (data) => {
                coopManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                coopManager.destroy(data)
            }
        }
    },
    {
        id: "sgs_farm:trapdoor",
        code: {
            onPlayerInteract: (data) => {
                trapdoorManager.interact(data);
            }
        }
    },
    {
        id: "sgs_farm:fish_trap",
        code: {
            onTick: (data) => {
                fishTrapManager.tick(data.block)
            },
            beforeOnPlayerPlace: (data) => {
                fishTrapManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                fishTrapManager.destroy(data)
            }
        }
    },
    /*
    {
        id: "sgs_farm:connectcardinal",
        code: {
            beforeOnPlayerPlace: (data) => {
                connectCardinalManager.beforeplace(data)
            },
            onPlayerDestroy: (data) => {
                connectCardinalManager.destroy(data)
            }
        }
    }
        */
];

const itemComponents = [
    {
        id: "sgs_farm:watering_can",
        code: {
            onBeforeDurabilityDamage: (data) => {
                wateringCanManager.beforeDurabilityDamage(data)
            },
            onUseOn: (data) => {
                wateringCanManager.onUseOn(data);
            }
        }
    },
    {
        id: "sgs_farm:sickle",
        code: {
            onUseOn: (data) => {
                sickleManager.onUseOn(data);
            }
        }
    }
]

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_farm_break_on_silktouch")) {
                data.cancel = true;
                mc.system.runTimeout(() => {
                    if (!(block.isValid())) return;
                    const loc = block.location;
                    block.dimension.runCommandAsync(`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.runCommandAsync(`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.runCommandAsync(`setblock ${loc.x} ${loc.y} ${loc.z} air [] destroy`);
                });
                return;
            };
        } catch { }
    });
}

let reload = 0;
function initBlockComponents() {
    mc.world.beforeEvents.worldInitialize.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() {
    if (mc.world.scoreboard.getObjective("sgs_farm_settings") === undefined) {
        mc.world.scoreboard.addObjective("sgs_farm_settings", "sgs_farm_settings");  //global settings
        mc.world.scoreboard.getObjective("sgs_farm_settings").setScore("CREATIVE_OVERRIDE", 0);

        mc.world.scoreboard.getObjective("sgs_farm_settings").setScore("SEED_CHANCE", 40);
        mc.world.scoreboard.getObjective("sgs_farm_settings").setScore("REGIONAL_SEEDS", 0);
        mc.world.scoreboard.getObjective("sgs_farm_settings").setScore("TRADER_SPAWN", 1);
        mc.world.scoreboard.getObjective("sgs_farm_settings").setScore("WILDFLOWER_BUSHES", 1);
    }

    //U3
    if (mc.world.scoreboard.getObjective("sgs_farm_animals") === undefined) {
        mc.world.scoreboard.addObjective("sgs_farm_animals", "sgs_farm_animals");  //animal settings
        mc.world.scoreboard.getObjective("sgs_farm_animals").setScore("ANIMAL_SPAWN", 1);
        mc.world.scoreboard.getObjective("sgs_farm_animals").setScore("HAT_TRANSFORM", 1)
    }
}