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


let onLoadStarted = false;
let onLoadFinished = false;
let onFirstLoadStarted = false;
let onFirstLoadFinished = false;
let onLoadFirstFinishTick = -100;
let nextIntervalTick = -100;

//Color bindings
const Orange = "§6";
const Red = "§4";
const Reset = "§r";
const Bold = "§l";

async function mainLoop() 
{
	if (system.currentTick == onLoadFirstFinishTick+20)
	{
		await utils.player0.addTag("onLoadFirstTimeFinished");
	}

	if (!onLoadStarted)
		await onLoad();
	else if (onLoadFinished)
		await onTick();

	system.run(mainLoop);
}


// High level flow - don't change this function!
async function onLoad()
{
	onLoadStarted = true;

	// First thing always - load player0
	await utils.onLoad();

	if (!utils.player0.hasTag("pu_se_first_load_started"))
	{
		await utils.player0.addTag("pu_se_first_load_started");
		if (await utils.player0.hasTag("pu_se_first_load_finished"))
			return;

		await game_events.onLoadFirstTime();

		await utils.player0.addTag("pu_se_first_load_finished");
		onLoadFirstFinishTick = system.currentTick;
	}

	// initialize modules
	await game_events.onLoad();

	// Subscribe to events
	world.afterEvents.itemUse.subscribe(game_events.onItemUse);
	world.afterEvents.entityHitEntity.subscribe(game_events.onEntityHurtEntity);
	world.afterEvents.entityHurt.subscribe(game_events.onEntityHurt);
	world.afterEvents.entitySpawn.subscribe(game_events.onEntitySpawn);
	world.afterEvents.projectileHitEntity.subscribe(game_events.onProjectileHitEntity);
	onLoadFinished = true;
}

// This function runs every tick (after load). Call onTick functionalities from here
async function onTick()
{
	await game_events.onTick();
}

system.run(mainLoop);

