//-----------------------------------------------------------------------------
// Torque Game Engine 
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------

// Functions dealing with connecting to a server


//-----------------------------------------------------------------------------
// Server connection error
//-----------------------------------------------------------------------------

addMessageCallback( 'MsgConnectionError', handleConnectionErrorMessage );

function handleConnectionErrorMessage(%msgType, %msgString, %msgError)
{
   // On connect the server transmits a message to display if there
   // are any problems with the connection.  Most connection errors
   // are game version differences, so hopefully the server message
   // will tell us where to get the latest version of the game.
   $ServerConnectionErrorMessage = %msgError;
}


//----------------------------------------------------------------------------
// GameConnection client callbacks
//----------------------------------------------------------------------------

$UnhaltTaskRunner = true;
function clientCmdMissionLoaded()
{
   Canvas.setContent($SplashLoadEnd);
   $MissionLoaded = true;
   if ($MissionWaiting == true)
   {
      $MissionWaiting = false;
      StopWaiting();
   }
   stopMissionLoad();
   if ($UnhaltTaskRunner == true)
   {
      TaskRunner.haltTasks(false);
   }
   $UnhaltTaskRunner = true;
   resetAudioHandles();
   
   if($PlayingGame) {
      loadMissionMusic();
   }
   else {
      loadMenuMusic();
   }
   
   // initialize the framerate check on the first game build
   if ($pref::Game::FirstTimePlaying == true)
   {
      $pref::Game::FirstTimePlaying = false;
      $FramerateCheck = true;
   }
   
   slgEnableQuitScreen();
}

function GameConnection::initialControlSet(%this)
{
   echo ("*** Initial Control Object");

   commandToServer('LoadServerManagers');

   // The first control object has been set by the server
   // and we are now ready to go.
   
   $ServerReady = true;

   unloadSelectionGroups();
   loadSelectionGroups();

   metrics("fps");

   if (isObject(PlayGui) == true)
   {
      PlayGui.loadAreaSelectImageLL("assets/client/ui/dotLL.png");
      PlayGui.loadAreaSelectImageLR("assets/client/ui/dotLR.png");
      PlayGui.loadAreaSelectImageUL("assets/client/ui/dotUL.png");
      PlayGui.loadAreaSelectImageUR("assets/client/ui/dotUR.png");
      PlayGui.loadAreaSelectImageTop("assets/client/ui/dotTop.png");
      PlayGui.loadAreaSelectImageBottom("assets/client/ui/dotBottom.png");
      PlayGui.loadAreaSelectImageLeft("assets/client/ui/dotLeft.png");
      PlayGui.loadAreaSelectImageRight("assets/client/ui/dotRight.png");
   }

   // load the portrait cameras
   if (LoadPortraitCameras() == false)
   {
      echo("Could not load portrait cameras");
   }

   // load the splash at the end of the game
   if ($SplashLoadEnd !$= "")
   {
      if ($SplashLoadEnd $= "MainMenuGui")
      {
         // this initializes the portrait cameras
         for (%index = 0; %index < $WW2HERO_COUNT; %index++)
         {
            %camera = GetPortraitCamera(%index);
            if (isObject(%camera) == false)
            {
               echo("Could not find a portrait camera for a hero");
               continue;
            }
            
            %component = %camera.getCameraCmp();
            if (isObject(%component) == false)
            {
               echo("Hero portrait camera found does not have a component");
               continue;
            }
            
            %hero = $HeroObject[%index];
            if (isObject(%hero) == false)
            {
               echo("Missing hero datablock for portrait cameras");
               continue;
            }
            
            %state = HeroCamera @ %index;
            if (isObject(%state) == false)
            {
               echo("Missing camera state to attach portrait camera to");
            }

            %state.camera = %camera;
            %component.setTarget(%hero.getId());
         }
      }
   }
   // default to main menu
   else
   {
      UnloadPortraitCameras();
      Canvas.setContent(MainMenuGui);
   }

   metrics("fps");
}

function GameConnection::setLagIcon(%this, %state)
{
   if (%this.getAddress() $= "local")
      return;
   LagIcon.setVisible(%state $= "true");
}

function GameConnection::onConnectionAccepted(%this)
{
   // >> Westward 2 CODE BLOCK
   clientBeginGame();
   // >> Westward 2 CODE BLOCK
}

function GameConnection::onConnectionTimedOut(%this)
{
   // Called when an established connection times out
   disconnectedCleanup();
   MessageBoxOK( "TIMED OUT", "The server connection has timed out.");
}

function GameConnection::onConnectionDropped(%this, %msg)
{
   // Established connection was dropped by the server
   disconnectedCleanup();
   MessageBoxOK( "DISCONNECT", "The server has dropped the connection: " @ %msg);
}

function GameConnection::onConnectionError(%this, %msg)
{
   // General connection error, usually raised by ghosted objects
   // initialization problems, such as missing files.  We'll display
   // the server's connection error message.
   disconnectedCleanup();
   MessageBoxOK( "DISCONNECT", $ServerConnectionErrorMessage @ " (" @ %msg @ ")" );
}


//----------------------------------------------------------------------------
// Connection Failed Events
//----------------------------------------------------------------------------

function GameConnection::onConnectRequestRejected( %this, %msg )
{
   switch$(%msg)
   {
      case "CR_INVALID_PROTOCOL_VERSION":
         %error = "Incompatible protocol version: Your game version is not compatible with this server.";
      case "CR_INVALID_CONNECT_PACKET":
         %error = "Internal Error: badly formed network packet";
      case "CR_YOUAREBANNED":
         %error = "You are not allowed to play on this server.";
      case "CR_SERVERFULL":
         %error = "This server is full.";
      case "CHR_PASSWORD":
         // XXX Should put up a password-entry dialog.
         if ($Client::Password $= "")
            MessageBoxOK( "REJECTED", "That server requires a password.");
         else {
            $Client::Password = "";
            MessageBoxOK( "REJECTED", "That password is incorrect.");
         }
         return;
      case "CHR_PROTOCOL":
         %error = "Incompatible protocol version: Your game version is not compatible with this server.";
      case "CHR_CLASSCRC":
         %error = "Incompatible game classes: Your game version is not compatible with this server.";
      case "CHR_INVALID_CHALLENGE_PACKET":
         %error = "Internal Error: Invalid server response packet";
      default:
         %error = "Connection error.  Please try another server.  Error code: (" @ %msg @ ")";
   }
   disconnectedCleanup();
   MessageBoxOK( "REJECTED", %error);
}

function GameConnection::onConnectRequestTimedOut(%this)
{
   disconnectedCleanup();
   MessageBoxOK( "TIMED OUT", "Your connection to the server timed out." );
}


//-----------------------------------------------------------------------------
// Disconnect
//-----------------------------------------------------------------------------

function removeGroupObjects(%group)
{
   if (isObject(%group) == false)
   {
      return;
   }
   
   for (%index = 0; %index < %group.getCount(); %index++)
   {
      %object = %group.getObject(%index);

      // remove any potential footprint that could be placed for the object
      RemoveObject(%object);
   }
}
