/*
Gamebots Pogamut derivation Copyright (c) 2010-2011, Michal Bida, Radek Pibil

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software must also be in compliance with the Epic Games Inc. license for mods which states the following: "Your mods must be distributed solely for free, period. Neither you, nor any other person or party, may sell them to anyone, commercially exploit them in any way, or charge anyone for receiving or using them without prior written consent of Epic Games Inc. You may exchange them at no charge among other end-users and distribute them to others over the Internet, on magazine cover disks, or otherwise for free." Please see http://www.epicgames.com/ut2k4_eula.html for more information.

*/
class GBPlayer extends UTPlayerController;

/**
 * Struct for specifying the camera key points - points the camera should fly through.
 */
struct CameraKeyPoint
{
	/** Target location of the key point. */
	var	vector					TargetLocation;
	/** Target rotation of the key point. */
	var	rotator				    TargetRotation;
	/** Will be filled up when first interpreting this key point. */
	var	vector					StartLocation;
	/** Will be filled up when first interpreting this key point. */
	var	rotator				    StartRotation;
	/** How much time shall the camera take when issuing commands reaching this key point. If it is set to -1 and bStatic to true it will be insta movement. */
	var	float					Duration;
	/** When should this movement start. -1 means it starts immediately as we try to interpret this CameraKeyPoint. */
	var	float					StartTime;
	/** Order of this key point. */
	var	int					    Order;
	/** True if we already set StartLocation and StartRotation. */
	var	bool				    bInitialized;
	/** Will only set camera to TargetLocation and TargetRotation. */
	var	bool				    bStatic;
};
/** Here we hold the key points we should fly through. */
var array<CameraKeyPoint> KeyPoints;

var int CurrentKeyPointIndex;

/** True if we are currently in camera mode (player can't move by himself) */
var bool bStoryCamera;

/** Set to true if we should start moving the StoryCamera according to the queue */
var bool bStoryCameraActive;

replication
{
	if (ROLE == ROLE_Authority)
		CurrentKeyPointIndex, bStoryCamera, bStoryCameraActive;

}

simulated function PostBeginPlay()
{
   Super.PostBeginPlay();
   //TestInitKeyPoints() ;
}

/** Exports key press to all control servers */
reliable server function SendKeyEvent(name InputKey, EInputEvent InputAction) 
{
	local string message;

    message = "KEYEVENT {PlayerId " $ string(self) $
		"} {PlayerName " $ self.PlayerReplicationInfo.PlayerName $
        "} {Key " $ InputKey $
        "} {Action " $ InputAction $ "}";	

	GBGameInterface(WorldInfo.Game).GetGameHandler().GlobalSendLine(message, true, false);
}

/*
* Adds one camera key point on client side.
*/
reliable client function AddCameraKeyPoint(int Order, int StartTime, int Duration, vector TargetLoc, rotator TargetRot, bool myStatic) {
	local CameraKeyPoint NewPoint;

	NewPoint.StartTime = StartTime;
	NewPoint.Duration = Duration;
	NewPoint.Order = Order;
	NewPoint.TargetLocation = TargetLoc;
	NewPoint.TargetRotation = TargetRot;
	NewPoint.bStatic = myStatic;

    //`log("GBPlayer.AddCameraKeyPoint():order:" $ order $ ";ST:" $ NewPoint.StartTime $ "Dur:" $ NewPoint.Duration $ ";TL:" $ TargetLoc);

	if (KeyPoints.Length < Order) {
		KeyPoints.Insert(KeyPoints.Length, newPoint.Order - KeyPoints.Length);
	}

	KeyPoints[newPoint.Order] = NewPoint;
}

/**
* Erase all camera key point on client side.
*/
reliable client function ClearCameraKeyPoints() {
	KeyPoints.Remove(0,KeyPoints.Length);
	CurrentKeyPointIndex = 0;
}

function TestInitKeyPoints() {

	local CameraKeyPoint keyPoint;

	keyPoint.Duration = 3;
	keyPoint.bStatic = true;
	keyPoint.TargetLocation = vect(0,0,0);
	keyPoint.TargetRotation = rot(0,0,0);
	keyPoint.StartTime = -1;
	keyPoint.Order = 0;
	KeyPoints[0] = keyPoint;

	keyPoint.Duration = 3;
	keyPoint.bStatic = false;
	keyPoint.TargetLocation = Vect(0,0,0);
	keyPoint.TargetRotation = Rot(0,32000,0);
	keyPoint.StartTime = -1;
	keyPoint.Order = 1;
	KeyPoints[1] = keyPoint;

	keyPoint.Duration = -1;
	keyPoint.bStatic = true;
	keyPoint.TargetLocation = Vect(0,0,-500);
	keyPoint.TargetRotation = Rot(0,0,0);
	keyPoint.StartTime = -1;
	keyPoint.Order = 2;
	KeyPoints[2] = keyPoint;

	keyPoint.Duration = 3;
	keyPoint.bStatic = false;
	keyPoint.TargetLocation = Vect(1000,1000,0);
	keyPoint.TargetRotation = Rot(16000,0,0);
	keyPoint.StartTime = -1;
	keyPoint.Order = 3;
	KeyPoints[3] = keyPoint;


}

state GBSpectating extends BaseSpectating
{
	ignores RestartLevel, Suicide, ThrowWeapon, NotifyPhysicsVolumeChange, NotifyHeadVolumeChange;

	exec function StartFire( optional byte FireModeNum )
	{
		ServerViewNextPlayer();
	}

	// Return to spectator's own camera.
	exec function StartAltFire( optional byte FireModeNum )
	{
		ResetCameraMode();
		ServerViewSelf();
	}

	event BeginState(Name PreviousStateName)
	{				
		local Rotator myRot;
		//Spawn Test Camera
		//self.ResetCameraMode();

		myRot = Rotation;
		//myRot.Pitch = 0;
		//myRot.Yaw = 0;
		myRot.Roll = 0;
		SetRotation(myRot);
		ClientSetRotation(myRot);

		`log("In GBSpectating:BeginState. prevSTate: "$PreviousStateName);
		if ( Pawn != None )
		{
			SetLocation(Pawn.Location);
			UnPossess();
		}
		bCollideWorld = true;
	}

	event EndState(Name NextStateName)
	{
		`log("In GBSpectating:EndState. nextSTate: "$NextStateName);
		if ( PlayerReplicationInfo != None )
		{
			if ( PlayerReplicationInfo.bOnlySpectator )
			{
				`log("WARNING - Spectator only player leaving spectating state to go to "$NextStateName);
			}
			PlayerReplicationInfo.bIsSpectator = false;
		}

		bCollideWorld = false;
		SpawnPlayerCamera();
	}

	/** overriding because of player being StoryFactor camera */
	function ProcessMove(float DeltaTime, vector NewAccel, eDoubleClickDir DoubleClickMove, rotator DeltaRot) {
		if (!bStoryCamera)
			super.ProcessMove(DeltaTime, NewAccel, DoubleClickMove, DeltaRot);
	}

	function UpdateRotation( float DeltaTime )
	{
		if (!bStoryCamera)
			super.UpdateRotation(DeltaTime);
		else if (bStoryCameraActive) 
			ComputeGBCameraMovement();
	}
}

/** This function handles player movement when we want to use him as a custom camera. */
simulated function ComputeGBCameraMovement() {
	local float CurrentTime, CustomDT, Ratio;
	local CameraKeyPoint CurrentKeyPoint;

	//time in ms
	CurrentTime = WorldInfo.TimeSeconds * 1000;
	//`log("KeyPoints.Length: " $ KeyPoints.Length);
	if (CurrentKeyPointIndex < KeyPoints.Length) {
		CurrentKeyPoint = KeyPoints[CurrentKeyPointIndex];
	} else {
		if (KeyPoints.Length == 0)
			`log("In:GBPlayer.ComputeGBCameraMovement(): KeyPoints.Length = 0!");
		return;
		//TestInitKeyPoints();
		//CurrentKeyPointIndex = 0;
		return;
	}
   
	`log("CurTime: " $ CurrentTime $ "; Index: " $ CurrentKeyPointIndex);
	//`log("CurrentKeyPoint:Loc: " $ CurrentKeyPoint.TargetLocation $ ";Rot: " $ CurrentKeyPoint.TargetRotation $ ";Dur: " $ CurrentKeyPoint.Duration);
	//`log("CurrentKeyPoint:StartTime: " $ CurrentKeyPoint.StartTime $ ";Static: " $ CurrentKeyPoint.bStatic $ ";Init: " $ CurrentKeyPoint.bInitialized);


	if (!CurrentKeyPoint.bInitialized) {
		//`log("In !CurrentKeyPoint.bInitialized");
		if (CurrentKeyPoint.Order > 0) {
			CurrentKeyPoint.StartLocation = KeyPoints[CurrentKeyPoint.Order - 1].TargetLocation;
			CurrentKeyPoint.StartRotation = KeyPoints[CurrentKeyPoint.Order - 1].TargetRotation;
		} else {
			CurrentKeyPoint.StartLocation = Location;
			CurrentKeyPoint.StartRotation = Rotation;
		}
		CurrentKeyPoint.bInitialized = true;				
		KeyPoints[CurrentKeyPoint.Order] = CurrentKeyPoint;
	}
	if (CurrentKeyPoint.StartTime == -1) {
		CurrentKeyPoint.StartTime = CurrentTime;
		KeyPoints[CurrentKeyPoint.Order] = CurrentKeyPoint;
	}

	//checking if this CurrentKeyPoint is active right now
	if ((CurrentKeyPoint.StartTime <= CurrentTime) && (CurrentKeyPoint.StartTime + CurrentKeyPoint.Duration >= CurrentTime) ){
		//move camera! 
		if (CurrentKeyPoint.bStatic) {		
			//`log("Setting CurrentKeyPoint.bStatic");
			SetRotation(CurrentKeyPoint.TargetRotation);
			SetLocation(CurrentKeyPoint.TargetLocation);			
		} else {
			CustomDT = CurrentTime - CurrentKeyPoint.StartTime;
			if (CurrentKeyPoint.Duration > 0)
				Ratio = CustomDT / CurrentKeyPoint.Duration;
			else
				Ratio = 0;

			//`log("Setting CurrentKeyPoint.bStatic=false");
			SetRotation(RLerp( CurrentKeyPoint.StartRotation, CurrentKeyPoint.TargetRotation, Ratio, true ));
			SetLocation(VLerp( CurrentKeyPoint.StartLocation, CurrentKeyPoint.TargetLocation, Ratio));												
		}		
	}

	//handles situation for instanteous static movement.
	if ((CurrentKeyPoint.bStatic) && (CurrentKeyPoint.StartTime <= CurrentTime) && (CurrentKeyPoint.StartTime + 1000 >= CurrentTime) && (CurrentKeyPoint.Duration == -1)) {
		//`log("Setting CurrentKeyPoint.bStatic Instant");
		SetRotation(CurrentKeyPoint.TargetRotation);
		SetLocation(CurrentKeyPoint.TargetLocation);
		CurrentKeyPoint.Duration = -2; //we store that we have done this movement
		KeyPoints[CurrentKeyPoint.Order] = CurrentKeyPoint;
		CurrentKeyPointIndex++;
	} else if (CurrentKeyPoint.StartTime + CurrentKeyPoint.Duration <= CurrentTime) { //check if we should switch to next CameraKeyPoint
		//`log("Increasing index");
		CurrentKeyPointIndex++;	
	}
}

simulated function ServerClientBecomeStoryCamera(){	
	if (PlayerCamera != none)
		PlayerCamera = none;

	if (!IsSpectating()) {
		ServerSuicide();
		GotoState('GBSpectating');	
	}
	bStoryCamera = true;
}

reliable server function ServerRemoteSpectate(){	
	//UTGame(WorldInfo.Game).BecomeSpectator(self);
	//PlayerReplicationInfo.bIsSpectator = true;
	//PlayerReplicationInfo.bOnlySpectator = true;			
		//PlayerCamera = Spawn(class'StoryFactoryCamera',self);
		//PlayerCamera.InitializeFor(self);	
	//ServerSpectate();
	if (self.IsInState('Dead')) {
		ServerRestartPlayer();
		//ServerSuicide();
	} else {
		ServerSuicide();
		GotoState('GBSpectating');	
	}
	

	//ClientGotoState('Spectating');
}

reliable server function ServerRemoteStopSpectate() {
	//PlayerReplicationInfo.bOnlySpectator = false;
	//if (!WorldInfo.Game.IsA('BotScenario'))
	//	UTGame(WorldInfo.Game).RestartPlayer(self);
	GotoState('Dead');	
}

DefaultProperties
{

}
