import { world, system, BlockVolume } from "@minecraft/server";
import { fo } from './utilities/fo_constants.js';

export function initAllTorches() {
    
    const interval = 217; 

    system.runInterval(() => {
        const overworld = fo.overworld;
        const players = overworld.getPlayers();
        const forebodingScore = fo.forebodingScore;

        if (players.length === 0) return;

        if (forebodingScore === -1) {

            for (const player of players) {
                scheduleRestoreTorchCommands(player); 
            }
        }

        
        const eventStart = fo.scoreChapter5 + (fo.durationChapter5 * 0.46) ; 
        const eventFinish = fo.scoreChapter5 + (fo.durationChapter5 * 0.95);

        if (forebodingScore >= eventStart && forebodingScore <= eventFinish) {
            for (const player of players) {
                scheduleFillCommands(player); 
            }
        }
    }, interval);

    function scheduleFillCommands(player) {
        const dim = player.dimension;
        const base = player.location;

        const offsets = [];
        for (let x = -48; x < 48; x += 16) {
            for (let y = -48; y < 48; y += 16) {
                for (let z = -48; z < 48; z += 16) {
                    offsets.push({
                        from: [x, y, z],
                        to: [
                            Math.min(x + 15, 48),
                            Math.min(y + 15, 48),
                            Math.min(z + 15, 48)
                        ]
                    });
                }
            }
        }

        const { min: minDY, max: maxDY } = dim.heightRange; 
        const players = world.getPlayers(); 

        offsets.forEach((offset, i) => {
            system.runTimeout(() => {
                try {
                    const fromY = Math.floor(base.y + offset.from[1]);
                    const toY = Math.floor(base.y + offset.to[1]);

                    
                    if (toY < minDY || fromY > maxDY) return;

                    const from = {
                        x: Math.floor(base.x + offset.from[0]),
                        y: Math.max(minDY, fromY),
                        z: Math.floor(base.z + offset.from[2])
                    };

                    const to = {
                        x: Math.floor(base.x + offset.to[0]),
                        y: Math.min(maxDY, toY),
                        z: Math.floor(base.z + offset.to[2])
                    };

                    
                    const center = {
                        x: (from.x + to.x) / 2,
                        y: (from.y + to.y) / 2,
                        z: (from.z + to.z) / 2
                    };

                    
                    for (const p of players) {
                        const dx = p.location.x - center.x;
                        const dy = p.location.y - center.y;
                        const dz = p.location.z - center.z;
                        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

                        if (distance <= 30) return; 
                    }

                    
                    const volume = new BlockVolume(from, to);
                    dim.fillBlocks(volume, "minecraft:light_block_0", {
                        blockFilter: { includeTypes: ["minecraft:torch"] },
                        ignoreChunkBoundErrors: true
                    });
                } catch (e) {
                    
                };
            }, i); 
        });
    }

    function scheduleRestoreTorchCommands(player) {
        const dim = player.dimension;
        const base = player.location;

        const offsets = [];
        for (let x = -48; x < 48; x += 16) {
            for (let y = -48; y < 48; y += 16) {
                for (let z = -48; z < 48; z += 16) {
                    offsets.push({
                        from: [x, y, z],
                        to: [
                            Math.min(x + 15, 48),
                            Math.min(y + 15, 48),
                            Math.min(z + 15, 48)
                        ]
                    });
                }
            }
        }

        const { min: minDY, max: maxDY } = dim.heightRange; 

        offsets.forEach((offset, i) => {
            system.runTimeout(() => {
                try {
                    const fromY = Math.floor(base.y + offset.from[1]);
                    const toY = Math.floor(base.y + offset.to[1]);

                    
                    if (toY < minDY || fromY > maxDY) return;

                    const from = {
                        x: Math.floor(base.x + offset.from[0]),
                        y: Math.max(minDY, fromY),
                        z: Math.floor(base.z + offset.from[2])
                    };

                    const to = {
                        x: Math.floor(base.x + offset.to[0]),
                        y: Math.min(maxDY, toY),
                        z: Math.floor(base.z + offset.to[2])
                    };

                    const volume = new BlockVolume(from, to);
                    
                    dim.fillBlocks(volume, "minecraft:torch", {
                        blockFilter: { includeTypes: ["minecraft:light_block_0"] },
                        ignoreChunkBoundErrors: true
                    });
                } catch (e) { console.warn(`error:${e} at restoring torches`) }
            }, i); 
        });
    }

}