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







export function initDaycycle() { 

    
    const
        chanceDaycycleStop = 1 / 15, 
        chanceDaycycleFF = 1 / 30, 
        forebodingCheck5 = fo.scoreChapter5, 
        forebodingCheck4 = fo.scoreChapter4, 
        checkInterval = 2407; 


    
    const
        forebodingCheck7 = -2410, 
        totalDayTime = 4, 
        backwardsFrequence = 1, 
        backwardsInterval = Math.floor(checkInterval / backwardsFrequence),

        BtimeStep = (24000 / ((totalDayTime * 20 * 60) / backwardsFrequence)); 


    if (fo.forebodingScore <= forebodingCheck7) { 

        timeBackwards()

    }

    
    system.runInterval(() => {

        if (fo.forebodingScore >= forebodingCheck4 && Math.random() <= chanceDaycycleStop) { 
            world.gameRules.doDayLightCycle = false;
            timeResume();
            return;
        };
        if (fo.forebodingScore >= forebodingCheck5 && Math.random() <= chanceDaycycleFF) timeFastForward(); 
        if (fo.forebodingScore <= forebodingCheck7) timeBackwards();

    }, checkInterval); 

    function timeFastForward() {
        const interval = system.runInterval(() => {
            let currentTime = world.getTimeOfDay();
            let chaoticTimeStep = Math.floor(Math.random() * 41) + 10; 

            if (currentTime >= 13200) {
                system.clearRun(interval); 
            } else {
                world.setTimeOfDay(currentTime + chaoticTimeStep); 
            }
        }, 1); 
    };

    function timeBackwards() {
        let sequence = 0;

        const interval = system.runInterval(() => {

            sequence++

            

            fo.overworld.runCommand(`time add ${-BtimeStep}`)
            

            if (sequence === backwardsInterval - 1) {

                system.clearRun(interval); 

            }

        }, backwardsFrequence);

        if (world.getAbsoluteTime() < 24000) {
            world.setAbsoluteTime(2399999);
        }

    };

    

    
    system.runTimeout(() => {
        world.gameRules.doDayLightCycle = true;
    }, 60)

    function timeResume() {

        system.runTimeout(() => {

            world.gameRules.doDayLightCycle = true;

        }, 6000); 
    }


}