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


export function initGamerules() {

    const
        forebodingCheck3 = fo.scoreChapter3,
        forebodingCheck5 = fo.scoreChapter5,
        forebodingCheck7 = fo.scoreChapter7;


    const currentTickSpeed = world.getDynamicProperty("currentTickSpeed");


    
    if (world.gameRules.doFireTick === false) world.gameRules.doFireTick = true;

    
    if (currentTickSpeed) {
        world.gameRules.randomTickSpeed = 1;

        world.setDynamicProperty("currentTickSpeed", false)
    };

    function chapter3(randomTick) {

        
        if (world.gameRules.randomTickSpeed && randomTick) {
            world.gameRules.randomTickSpeed = false;

            
        }

    };

    function chapter5() {

        
        if (world.gameRules.naturalRegeneration) {
            world.gameRules.naturalRegeneration = false;

            
        }

        
        if (world.getDifficulty() != "Hard") {
            world.setDifficulty("Hard")

            
        }

    };

    function chapter7(randomTick) {

        chapter3(randomTick);
        chapter5();

        
        const players = world.getAllPlayers();

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

        for (const player of players) {
            const gameMode = player.getGameMode();
            if (gameMode === "Creative" || gameMode === "Spectator") {
                player.setGameMode(GameMode.Survival);
            }

        }
        

        
        if (world.gameRules.doMobSpawning) {
            world.gameRules.doMobSpawning = false;

            
        }

        
        if (world.gameRules.doDayLightCycle) {
            world.gameRules.doDayLightCycle = false;

            
        }


    };

    system.runInterval(() => {
        const forebodingScore = fo.forebodingScore;
        const randomTick = fo.randomTick

        if (forebodingScore <= forebodingCheck7) {
            chapter7(randomTick);
        } else {

            if (forebodingScore >= forebodingCheck3) {
                chapter3(randomTick);
                if (forebodingScore >= forebodingCheck5) {
                    chapter5();
                }
            }
        }

    }, 5)


};