#include "scripts/common.txt"
#include "scripts/Math.txt"
#include "scripts/BP_Input.txt"
#include "scripts/BP_TimeRecord.txt"
#include "scripts/BP_TimeGhostData.txt"

//BP Recorded Ghost Time = 2298.532959; //38:18.53

const bool BP_IS_RECORDING = false;
const float BP_RECORD_TIME = 0.25f;

const float HUD_TIMER_SCALE = 1.0f;
const float HUD_TIMER_MS_SCALE = 0.5f;
const float HUD_TIMER_OFFSETX = 4.0f;
const float HUD_TIMER_OFFSETY = 5.0f;
const float HUD_TIMER_OFFSETY_LB = 96.0f + HUD_TIMER_OFFSETY;
const int HUD_TIMER_MSTEXT_ID = 0;
const int HUD_TIMER_TEXT_ID = 1;
const int HUD_PIC_BG_ID = 0;

const kStr BPTimeGVTimeKey = "BP_SpeedTimer";
const kStr BPTimeGVDoneKey = "BP_SpeedTimerDone";

enum BPTimeChars
{
	BP_TIME_BG = 0,
    BP_TIME_MS1,
	BP_TIME_MS2,
	BP_TIME_P1,
	BP_TIME_S1,
	BP_TIME_S2,
	BP_TIME_C1,
	BP_TIME_M1,
	BP_TIME_M2,
	BP_TIME_C2,
	BP_TIME_H1,
    
    NUM_BP_TIME_CHARS
}

array<BP_TimeRecord> records;
float recordTime;

class BP_Time : ScriptObject
{
    kActor @self;
	float time;
	float startTime;
	array<kActor@> chars;
	bool complete; // if true game is beat. run finished.
    bool startedIntro;
	kActor@ ghost;
	kActor@ campaigner;
	array<BP_TimeRecord> ghostRecords;
	float ghostStartTime;
	float ghostEndTime;
	bool ghostMissed;
	int lastGhostStateFlags;
	uint recordStateFlags;
	bool didSpecial1;
	bool didSpecial2;
	uint16 buttons;
    bool deactive;
	//------------------------------------------------------------------------------------------------------------------------
    BP_Time(kActor @actor)
	{
        @self = actor;
		self.Flags() |= AF_ALWAYSACTIVE;
        deactive = false;
		
		records.resize(0);
		recordTime = 0.0f;
		
		//On new game reset time
		bool isNewGame;
		GameVariables.GetBool("g_newgame", isNewGame);
		GameVariables.GetBool("bStartedHubIntro", startedIntro);
		if (isNewGame)
		{
			GameVariables.SetValue(BPTimeGVTimeKey, "0");
			GameVariables.SetValue(BPTimeGVDoneKey, "0");
			time = 0.0f;
			complete = false;
		}
		
		//Get Time
		if (!GameVariables.GetFloat(BPTimeGVTimeKey, time, 0.0f))
		{
			GameVariables.Add(BPTimeGVTimeKey, "" + time);
		}
		//Get Time Is Done
		if (!GameVariables.GetBool(BPTimeGVDoneKey, complete, false))
		{
			GameVariables.Add(BPTimeGVDoneKey, "0");
		}

		//Remove if at intro maps or title map or gallery
		if(Game.GetCurrentMapID() == 50 ||
            (Game.GetCurrentMapID() >= 42 && Game.GetCurrentMapID() <= 46))
		{
            deactive = true;
			// self.Remove();
			return;
		}
				
		startTime = time;
		recordTime = time % BP_RECORD_TIME;
		
		@ghost = ActorFactory.Spawn("BP_Time_Ghost", 0.0f, 0.0f, 0.0f, 0.0f);
        ghost.SetPosition(kVec3(0.0f, 0.0f, 0.0f));
		ghost.Scale() = kVec3(0.2f, 0.2f, 0.2f);
		ghost.Flags() |= AF_NODRAW;
		ghost.AnimState().Set(anim_aiStanding, 8.0f, ANF_LOOP);
		ghost.AnimState().SetLastFrame();
		
		int variation = TV_NONE;
		switch (Math::RandMax(3))
		{
			case 0:
				variation = TV_KNIFE;
				break;
			case 1:
				variation = TV_BOW;
				break;
			default:
				variation = TV_NONE;
				break;
		}
		ghost.ModelVariation() = variation;
		
		//get ghost data for this map
		ghostRecords = BP_GetGhostData(Game.GetCurrentMapID(), time, ghostStartTime, ghostEndTime);
		ghostMissed = (time >= ghostEndTime);
    }
	//------------------------------------------------------------------------------------------------------------------------
    void OnSpawn() {}
	//------------------------------------------------------------------------------------------------------------------------
	void OnPostBeginLevel()
	{
        if(deactive)
        {
            return;
        }
        
	}
	//------------------------------------------------------------------------------------------------------------------------
	void OnEndLevel()
	{
        if(deactive)
        {
            return;
        }

		GameVariables.SetValue(BPTimeGVTimeKey, "" + time);
		GameVariables.SetValue(BPTimeGVDoneKey, complete ? "1" : "0");
		OutputRecords();
	}
	//------------------------------------------------------------------------------------------------------------------------
	void RecordGame()
	{
		if (!BP_IS_RECORDING)
			return;
		
		recordTime += GAME_DELTA_TIME;
		if (recordTime >= BP_RECORD_TIME)
		{
			recordTime -= BP_RECORD_TIME;
			int stateFlags = 0;
			kPuppet@ puppet = Player.Actor();
			if (puppet.GetWaterLevel() == WLT_UNDER) recordStateFlags |= BPTRS_Underwater;
			if (!Math::Vec3Approximately(puppet.Velocity(), 0.0f)) recordStateFlags |= BPTRS_Move;
			if (didSpecial1) recordStateFlags |= BPTRS_Special1;
			if (didSpecial2) recordStateFlags |= BPTRS_Special2;
			records.insertLast(BP_TimeRecord(puppet.Origin(), puppet.Yaw(), recordStateFlags));
			didSpecial1 = false;
			didSpecial2 = false;
			recordStateFlags = 0;
		}
	}
	//------------------------------------------------------------------------------------------------------------------------
	void OutputRecords()
	{
		if (!BP_IS_RECORDING)
			return;

		Sys.Print("<A>Map " + Game.GetCurrentMapID());
		Sys.Print(" | startTime = " + startTime + "; endTime = " + time + "; ");
		Sys.Print("return array<BP_TimeRecord>={");
		for (uint i = 0; i < records.length(); i++)
		{
			Sys.Print(records[i].ToOutputString() + ((i == records.length() - 1) ? "" : ","));
		}
		Sys.Print("};");
		Sys.Print("</A>");
	}
	//------------------------------------------------------------------------------------------------------------------------
	void PlaySoundGhostClimb()
	{
		switch(Math::RandMax(2))
		{
		case 0:
			ghost.PlaySound("sounds/shaders/turok_climb_1.ksnd"); //generic_23_turok_climb_1
			break;
		case 1:
			ghost.PlaySound("sounds/shaders/turok_climb_2.ksnd"); //generic_23_turok_climb_2
			break;
		}
	}
	//------------------------------------------------------------------------------------------------------------------------
    void DrawTimer()
    {
        // Get HUD Opacity
        kStr sHudOpacity;
        Sys.GetCvarValue("hud_opacity", sHudOpacity);
        int hudOpacity = sHudOpacity.Atoi();
        
        // Get Time
        int hours, minutes, seconds, ms;
		if(time < 0.0f || time >= 36000.0f)
        {
            hours = 9;
            minutes = 59;
            seconds = 59;
            ms = 99;
        }
        else
        {
            int iTime = int(time);
            int remainingTime = iTime % 3600;
            hours = iTime / 3600;
            minutes = remainingTime / 60;
            seconds = remainingTime % 60;
            ms = int((time - iTime) * 100.0f);
        }

        // Get Text
        kStr text;
        kStr msText = "." + (ms / 10) + "" + (ms % 10);
        if(hours >= 1)
        {
            text = "" + hours + ":" + (minutes / 10) + "" + (minutes % 10) + ":" + (seconds / 10) + "" + (seconds % 10);// + "." + (ms / 10) + "" + (ms % 10);
        }
        else if(minutes >= 10)
        {
            text = "" + (minutes / 10) + "" + (minutes % 10) + ":" + (seconds / 10) + "" + (seconds % 10);// + "." + (ms / 10) + "" + (ms % 10);
        }
        else if(minutes >= 1)
        {
            text = "" + (minutes % 10) + ":" + (seconds / 10) + "" + (seconds % 10);// + "." + (ms / 10) + "" + (ms % 10);
        }
        else if(seconds >= 10)
        {
            text = "" + (seconds / 10) + "" + (seconds % 10);// + "." + (ms / 10) + "" + (ms % 10);
        }
        else
        {
            text = "" + (seconds % 10);// + "." + (ms / 10) + "" + (ms % 10);
        }
        
        float textWidth, textHeight, msTextWidth, msTextHeight;
        Game.GetTextSize(text, GFT_BIG, HUD_TIMER_SCALE, textWidth, textHeight);
        Game.GetTextSize(msText, GFT_BIG, HUD_TIMER_MS_SCALE, msTextWidth, msTextHeight);
        
        float x = HUD_TIMER_OFFSETX;
        float y = HUD_TIMER_OFFSETY;
        
		//Position the chars so they won't get cutoff from cutscene letterbox
		if(Camera.Active())
		{
            // if((Camera.Flags() & CMF_NO_LETTERBOX) == 0)
            // {
                // y = HUD_TIMER_OFFSETY_LB;
            // }
            // if((Camera.Flags() & CMF_SHOW_CREDITS) != 0)
            // {
                // // Draw background
            // }
            
            switch (Game.GetCurrentMapID())
            {
                case 2: //ending credits map
                    // Draw background
                    break;
                case 5: //start intro has no letterbox
                    if (!startedIntro)
                    {
                    }
                    else //other cutscene (example: dying)
                    {
                        y = HUD_TIMER_OFFSETY_LB;
                    }
                    break;
                default: //assume every other cutscene has letterbox
                    y = HUD_TIMER_OFFSETY_LB;
                    break;
            }
		}
        
        // Draw background
        // Game.AddPic(HUD_PIC_BG_ID, "textures/texff000000.png",
            // 640.0f - textWidth - msTextWidth - x, y,
            // textWidth + msTextWidth, textHeight, 2);

        // Draw Text
        Game.AddText(HUD_TIMER_MSTEXT_ID, GFT_BIG, msText,
            640.0f - msTextWidth - x, y + textHeight - msTextHeight,
            2, HUD_TIMER_MS_SCALE, false, true, 255, 255, 255, hudOpacity, 255, 255, 255, hudOpacity);
        Game.AddText(HUD_TIMER_TEXT_ID, GFT_BIG, text,
            640.0f - textWidth - msTextWidth - x, y,
            2, HUD_TIMER_SCALE, false, true, 255, 255, 255, hudOpacity, 255, 255, 255, hudOpacity);
    }
	//------------------------------------------------------------------------------------------------------------------------
    void OnTick()
	{
        if(deactive)
        {
            return;
        }

		if (!complete)
		{
			time += GAME_DELTA_TIME;
			GameVariables.SetValue(BPTimeGVTimeKey, "" + time); //because of saving/loading need to do this every tick
			
			RecordGame();
			
			//check for beat game conditions to stop the timer
			if(Game.GetCurrentMapID() == 0) //campaigner
			{
				if(@campaigner == null)
                {
					@campaigner = World.GetActorByTID(400);
                }
				if(campaigner !is null && campaigner.Health() <= 0)
				{
					complete = true;
				}
			}
			else if(Game.GetCurrentMapID() == 47) //tutorial
			{
				const int areaID = Player.Actor().AreaID();
				int areaFlags = World.GetAreaFlags(areaID);
				if ((areaFlags & AAF_EVENT) != 0 && World.GetAreaArg(areaID, 3) == 10021)
				{
					complete = true;
				}
			}
		}

		//position ghost
		if (!ghostMissed && time >= ghostStartTime)
		{
			float dTime = (time - ghostStartTime);
			float fGhostIndex = (time - ghostStartTime) / BP_RECORD_TIME;
			int ghostIndex = int(fGhostIndex);
			int ghostRecordsLength = int(ghostRecords.length());
			if (ghostIndex >= 0 && ghostIndex < ghostRecordsLength - 1)
			{
				ghost.Flags() &= ~AF_NODRAW;
				float t = (dTime % BP_RECORD_TIME) / BP_RECORD_TIME;
				int ghostNextIndex = ghostIndex + 1;
				ghost.Origin().x = Math::Lerp(ghostRecords[ghostIndex].origin.x, ghostRecords[ghostNextIndex].origin.x, t);
				ghost.Origin().y = Math::Lerp(ghostRecords[ghostIndex].origin.y, ghostRecords[ghostNextIndex].origin.y, t);
				ghost.Origin().z = Math::Lerp(ghostRecords[ghostIndex].origin.z, ghostRecords[ghostNextIndex].origin.z, t);
				ghost.Yaw() = kAngle(ghostRecords[ghostIndex].yaw).Interpolate(ghostRecords[ghostNextIndex].yaw, t);
				
				//play animations/sounds depending on stateFlags
				if ((ghostRecords[ghostIndex].stateFlags & BPTRS_Jump) != 0 && (lastGhostStateFlags & BPTRS_Jump) == 0)
				{
					ghost.PlaySound("sounds/shaders/turok_jump.ksnd"); //generic_21_turok_jump.ksnd
				}
				if ((ghostRecords[ghostIndex].stateFlags & BPTRS_ClimbThrust) != 0 && (lastGhostStateFlags & BPTRS_ClimbThrust) == 0)
				{
					PlaySoundGhostClimb();
				}
				if ((ghostRecords[ghostIndex].stateFlags & BPTRS_Death) != 0 && (lastGhostStateFlags & BPTRS_Death) == 0)
				{
					ghost.PlaySound("sounds/shaders/generic_18_turok_normal_death.ksnd");
				}
				if ((ghostRecords[ghostIndex].stateFlags & BPTRS_Special1) != 0 && (lastGhostStateFlags & BPTRS_Special1) == 0)
				{
					ghost.PlaySound("sounds/shaders/turok_i_am.ksnd");
				}
				if ((ghostRecords[ghostIndex].stateFlags & BPTRS_Special2) != 0 && (lastGhostStateFlags & BPTRS_Special2) == 0)
				{
					ghost.PlaySound("sounds/shaders/talset_ashamed.ksnd");
				}
				
				lastGhostStateFlags = ghostRecords[ghostIndex].stateFlags;
			}
			else
			{
				if ((ghost.Flags() & AF_NODRAW) == 0)
				{
					ghost.Flags() |= AF_NODRAW;
					// Game.SpawnFx("fx/regeneration_appearance.kfx", ghost.Origin(), ghost.GetSectorIndexAtLocation(ghost.Origin()));
					// Game.SpawnFx("fx/regeneration_appearance.kfx", ghost.Origin(), World.FindNextClosestSector(ghost.Origin()));
					Game.SpawnFx("fx/regeneration_appearance.kfx", ghost.Origin(), -1);
				}
			}
		}
		
		if (BP_IS_RECORDING)
		{
			kPuppet@ puppet = Player.Actor();
			if ((puppet.PlayerFlags() & PF_DEAD) != 0 && (recordStateFlags & BPTRS_Death) == 0) recordStateFlags |= BPTRS_Death;
			if ((puppet.PlayerFlags() & PF_JUMPING) != 0 && (recordStateFlags & BPTRS_Jump) == 0) recordStateFlags |= BPTRS_Jump;
			if ((puppet.PlayerFlags() & PF_CRAWLING) != 0 && (recordStateFlags & BPTRS_Crawl) == 0) recordStateFlags |= BPTRS_Crawl;
			if ((puppet.PlayerFlags() & PF_FIREDPROJECTILE) != 0 && (recordStateFlags & BPTRS_Shoot) == 0) recordStateFlags |= BPTRS_Shoot;
			if ((puppet.PlayerFlags() & PF_CLIMBTHRUST) != 0 && (recordStateFlags & BPTRS_ClimbThrust) == 0) recordStateFlags |= BPTRS_ClimbThrust;

			buttons = InputUpdate(buttons);
			if (InputMapZoomInDown())
			{
				didSpecial1 = true;
				puppet.PlaySound("sounds/shaders/turok_i_am.ksnd");
			}
			if (InputMapZoomOutDown())
			{
				didSpecial2 = true;
				puppet.PlaySound("sounds/shaders/talset_ashamed.ksnd");
			}
		}

        DrawTimer();
    }
	//------------------------------------------------------------------------------------------------------------------------
}
