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_sg_first_load_started"))
	{
		await utils.player0.addTag("pu_sg_first_load_started");
		if (await utils.player0.hasTag("pu_sg_first_load_finished"))
			return;

		await game_events.onLoadFirstTime();

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

	// initialize modules
	await game_events.onLoad();

	// Subscribe to events
	//world.beforeEvents.entityRemove.subscribe(game_events.onEntityRemove);
	world.afterEvents.entitySpawn.subscribe(game_events.onEntitySpawn);
	//world.afterEvents.itemStartUse.subscribe(game_events.onItemStartUse);
	world.afterEvents.itemReleaseUse.subscribe(game_events.onItemReleaseUse);
	world.afterEvents.itemUse.subscribe(game_events.onItemUse);
	world.afterEvents.itemUseOn.subscribe(game_events.onItemUseOn);
	//world.afterEvents.itemStopUse.subscribe(game_events.onItemStopUse);
	//world.afterEvents.projectileHitBlock.subscribe(game_events.onProjectileHitBlock);
	//world.afterEvents.playerJoin.subscribe(game_events.onPlayerJoin);
	//world.afterEvents.playerSpawn.subscribe(game_events.onPlayerSpawn);
	//world.afterEvents.entityDie.subscribe(game_events.onEntityDie);
	//world.afterEvents.playerInteractWithEntity.subscribe(game_events.onPlayerInteractWithEntity);
	world.afterEvents.itemCompleteUse.subscribe(game_events.onitemCompleteUse);
	world.afterEvents.entityHurt.subscribe(game_events.onEntityHurt);
	onLoadFinished = true;
}

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

system.run(mainLoop);

