import { system, world } from "@minecraft/server";
import * as game from "./game";
import * as game_features from "./game_features";

let scoreboard = world.scoreboard;

let onLoadDone = false;
let onLoadFirstTimeStarted = false;
let onLoadFirstTimeFinished = false;
let onLoadFirstFinishTick = -100;
let nextIntervalTick = -100;

async function mainLoop() 
{
	if (system.currentTick == onLoadFirstFinishTick+20)
	{
		await game.host.addTag("onLoadFirstTimeFinished");
	}
	
	if (!onLoadDone)
		await onLoad();
	else
		await onTick();
	
	system.run(mainLoop);
}

// This function runs once per world, on the frist session
async function onLoadFirstTime() 
{
	onLoadFirstTimeStarted = true;
	let firstLoadFinished = scoreboard.getObjective("tcs_cba_FirstLoadFinished");
	if (firstLoadFinished)
		return;
	
  
	await game.onLoadFirstTime(); // this function replaces the old init_bedrock function
	
	
	firstLoadFinished = await scoreboard.addObjective("tcs_cba_FirstLoadFinished", "tcs_cba_FirstLoadFinished");
	onLoadFirstFinishTick = system.currentTick;
}

// This function runs once per session
// Add onLoad() and subscribes here. Don't make other changes to this function
async function onLoad() 
{
	if (onLoadDone)
		return;
	onLoadDone = true;
	
	await game.loadHost();
	
	if (!onLoadFirstTimeStarted)
		await onLoadFirstTime() ;
	
	// initialize modules
	await game_features.onLoad();
	
	// Subscribe to events here
	world.afterEvents.playerSpawn.subscribe(game_features.onPlayerSpawn);
	world.afterEvents.itemUse.subscribe(game_features.onItemUse);
	system.afterEvents.scriptEventReceive.subscribe(game_features.onScriptEventReceive);
}

// This function runs every tick (after load finished). Call main game loop and other code from here
async function onTick()
{
	await game_features.onTick(); 
	
    if(system.currentTick >= nextIntervalTick)
	{
		nextIntervalTick = system.currentTick + 20;
		for(let player of world.getAllPlayers()) 
		{
			if (player === undefined)
				continue;
			if (!player.hasTag('tcs_cba_got_book') )
			{
				game.runPlayerCommand(player, `structure load tcs_cba:book ~ ~ ~`);
				game.runPlayerCommand(player, `structure load tcs_cba:starter_kit_item ~ ~ ~`);
				player.addTag('tcs_cba_got_book');
			}
		}
	}
}

system.run(mainLoop);