// Force compile of our scripts
compile("scripts/projectiles.cs");
compile("scripts/item.cs");
compile("scripts/vehicles/vehicle_tank.cs");
compile("scripts/weapons/mortar.cs");
compile("scripts/camera.cs");
compile("scripts/CTFGame.cs");
compile("scripts/defaultGame.cs");
compile("scripts/deployables.cs");
compile("scripts/gameBase.cs");
compile("scripts/inventoryHud.cs");
compile("scripts/player.cs");

// NEW CODE - LETHAL_E
function serverCmdTeleportToBeacon(%obj, %beacon)
{
         // moves %obj to %beacon's location and
         // loads them up with their currently
         // selected loadout

         if(!$AllowBeaconFeatures)
            return;
            
         // first check if indeed we have a beacon
         if(%beacon > $BeaconIndex[%obj.team])
                    return;

         // Move player to beacon position
         %obj.player.setTransform($BeaconLocations[%obj.team, %beacon]);
         // Make speed = 0
         %obj.player.setVelocity("0 0 0");
         // Load client with their selected inventory
         buyFavorites(%obj);
         // Give them full life and full energy
         %obj.player.setDamageLevel(0);
         %obj.player.setEnergyLevel(10000); // use some huge value to give max amount
         
         // if they have the flag... return it
         if(%obj.player.holdingFlag)
         {
              serverCmdReturnFlags(%obj, %obj.player.holdingflag.team);
         }
}

// NEW CODE - LETHAL_E
function serverCmdSpawnVehicleAtBeacon(%obj, %beacon, %blockName)
{
   if(!$AllowBeaconFeatures)
      return;
      
   // first check if indeed we have a beacon
   if(%beacon > $BeaconIndex[%obj.getSensorGroup()])
       return;
       
   // spawns a vehicle at the beacon
   %team = %obj.getSensorGroup();
   if(vehicleCheck(%blockName, %team))
   {
       // Retrieve beacon position and rotation
       %position =  posFromTransform($BeaconLocations[%obj.team, %beacon]);
       %rotation =  rotFromTransform($BeaconLocations[%obj.team, %beacon]);

       %position = vectorAdd(%position, %blockName.spawnOffset);

       // Check to see if we're in the clear... terrain wise
       %mask = $TypeMasks::TerrainObjectType;
       InitContainerRadiusSearch(%position, %blockName.checkRadius, %mask);
       
       // Loop until we get high enough...
       // WARNING ENDLESS LOOP POSSIBLE
       while(%objfound = containerSearchNext() != 0)
       {
           // add some height...
           %position = vectorAdd(%position, %blockName.spawnOffset);
       }
       
       %o = %blockName.create(%team);
       if(%o)
       {
              %o.team = %team;

              vehicleListAdd(%blockName, %o);
              MissionCleanup.add(%o);

              %o.setTransform(%position @ " " @ %rotation);

              if(%obj.player.lastVehicle)
              {
                     %obj.player.lastVehicle.lastPilot = "";
                     vehicleAbandonTimeOut(%obj.player.lastVehicle);
                     %obj.player.lastVehicle = "";
              }
              %obj.player.lastVehicle = %o;
              %o.lastPilot = %obj.player;

              %o.getDataBlock().schedule(2000, "mountDriver", %o, %obj.player);

              if(%o.getTarget() != -1)
                   setTargetSensorGroup(%o.getTarget(), %obj.getSensorGroup());
       }
    }
}

// NEW CODE - LETHAL_E
function serverCmdRepairBase(%obj, %team)
{
         // this code snippet repairs %team's base
         %temp = %obj.getSensorGroup();
         
         if(%team == 2)
         {
            // repair enemy's base
            echo("team was enemy");
            if(%temp == 1)
               %temp = 2;
            else
               %temp = 1;
         }
         
         %team = %temp;
         
         $TKBRepair = "BASE";
         $TKBTeam = %team;
         %group = nameToId("MissionGroup/Teams");
         %group.ObjectRestore();

         //%group = nameToId(%team);
         //RecursiveMissionWalkInit();
         //RecursiveMissionWalk(%group, 0);
         //
         //for(%x = 0; %x < $TKBMissionWalkCount; %x++)
         //{
         //    %gameobj = $TKBMissionWalk[%x];
         //    %name = %gameobj.getDataBlock().getName();
         //   if(%name $= "StationInventory" || %name $= "GeneratorLarge" ||
         //       %name $= "SensorMediumPulse" || %name $= "StationVehiclePad" ||
         //       %name $= "SensorLargePulse")
         //    {
         //       // we found a base object... repair it to full life
         //       %gameobj.setDamageLevel(0);
         //       %gameobj.setDamageState(Enabled);
         //    }
         //}
}

function serverCmdRepairTurrets(%obj, %team)
{
         // this code snippet repairs %team's turrets
         %temp = %obj.getSensorGroup();

         if(%team == 2)
         {
            // repair enemy's base
            if(%temp == 1)
               %temp = 2;
            else
               %temp = 1;
         }

         %team = %temp;
         
         $TKBRepair = "TURRETS";
         $TKBTeam = %team;
         %group = nameToId("MissionGroup/Teams");
         %group.ObjectRestore();

         //%group = nameToId(%team);
         //RecursiveMissionWalkInit();
         //RecursiveMissionWalk(%group, 0);
         //
         //for(%x = 0; %x < $TKBMissionWalkCount; %x++)
         //{
         //       %gameobj = $TKBMissionWalk[%x];
         //       //if(%gameobj.getDataBlock)
         //       //{
         //           %name = %gameobj.getDataBlock().getName();
         //          if(%name $= "SentryTurret" || %name $= "TurretBaseLarge")
         //           {
         //                // we found a turret object... repair it to full life
         //                %gameobj.setDamageLevel(0);
         //                %gameobj.setDamageState(Enabled);
         //           }
         //       //}
         //}
}

function RecursiveMissionWalkInit()
{
         // basically just reset values
         $TKBMissionWalk = -1;
         $TKBMissionWalkCount = 0;
}
function RecursiveMissionWalk(%group, %index)
{
         // used because some maps ARE FUCKING GAY
         // and don't follow the same format
         %obj = %group.getObject(%index);
         if(!isObject(%obj))
         {
             // recursive exit
             return;
         }
             
         %count = %obj.getCount();
         if(%count > 0)
         {
             // another fucking simgroup or something
             RecursiveMissionWalk(%obj, 0);
             RecursiveMissionWalk(%group, %index+1);
         }
         else
         {
            // %obj isn't another group (WHOO HOO)
            $TKBMissionWalk[$TKBMissionWalkCount] = %obj;
            $TKBMissionWalkCount++;
            RecursiveMissionWalk(%group, %index+1);
         }
}

function serverCmdRepairRemoteEquipment(%obj, %team)
{
         // this code snippet repairs %team's turrets
         %temp = %obj.getSensorGroup();

         if(%team == 2)
         {
            // repair enemy's base
            if(%temp == 1)
               %temp = 2;
            else
               %temp = 1;
         }
         %team = %temp;
         
         $TKBRepair = "REMOTES";
         $TKBTeam = %team;
         %group = nameToId("MissionCleanup/Deployables");
         %group.ObjectRestore();
         
         //%depCount = 0;
         //%depGroup = nameToID("MissionCleanup/Deployables");
         //if (%depGroup > 0)
         //   %depCount = %depGroup.getCount();
         //
         // loop through objects
         //for(%x = 0; %x < %depCount; %x++)
         //{
         //       %depObj = %depGroup.getObject(%x);
         //       %name = %depObj.getDataBlock().getName();
         //       if(%name $= "DeployedStationInventory" || %name $= "DeployedMotionSensor" ||
         //          %name $= "DeployedPulseSensor" || %name $= "TurretDeployedOutdoor" ||
         //          %name $= "TurretIndoorDeployable" || %name $= "TurretDeployedFloorIndoor" ||
         //          %name $= "TurretDeployedWallIndoor" || %name $= "TurretDeployedCeilingIndoor")
         //       {
         //          if(%depObj.team == %team)
         //          {
         //              // repair this bitch
         //             %depObj.setDamageLevel(0);
         //             %depObj.setDamageState(Enabled);
         //          }
         //       }
         //}
}

function serverCmdValidateScript(%obj)
{
         // callback function to make sure they have the
         // script installed
         for(%x = 0; %x < ClientGroup.getCount(); %x++)
         {
                %o = ClientGroup.getObject(%x);
                if(%o == %obj)
                {
                      echo("Validated client: " @ %obj);
                      %o.validated = true;
                }
         }
}

function ValidateClient(%client)
{
         // validates the client
         for(%x = 0; %x < ClientGroup.getCount(); %x++)
         {
                %o = ClientGroup.getObject(%x);
                if(%o == %client)
                {
                      if(%o.validated == false)
                      {
                             centerprint(%client, "\nYou do not have the TKBPractice Mod local script\nYou will not be able to use most of the features\n", 5, 3);
                      }
                      return;
                }
         }
         centerprint(%client, "\nYou do not have the TKBPractice Mod local script\nYou will not be able to use most of the features\n", 5, 3);
}

// default to 0
$TKBEquipmentListCount = 0;

function serverCmdLoadEquipment(%obj, %num)
{
         // Load equipment from a file
         // and deploy them on the map
         
         // get the team
         %team = %obj.getSensorGroup();

         %file = new FileObject();
         %filename = "Team" @ %team @ $CurrentMission @ %num @ ".cs";
         if(%file.openForRead("prefs/" @ %filename))
         {
             // it exists, exec it
             exec("prefs/" @ %filename);
             
             for(%x = 0; %x < $TKBEquipmentListCount; %x++)
             {
                  // create the actual deployable
                  %item = $TKBEquipmentListDataBlockClassName[%x];
                  %rot = rotFromTransform($TKBEquipmentListPos[%x]);

                  echo("item: " @ %item);
                  if(%item $= "TurretData")
                  {
                     %className = "Turret";
                  }
                  else
                  {
                     %className = "StaticShape";
                  }

                  %deplObj = new (%className)() {
                       dataBlock = $TKBEquipmentListDataBlockName[%x];
                  };

                  // set orientation (do not do the deployable rotation...)
                  %deplObj.setTransform(posFromTransform($TKBEquipmentListPos[%x]) SPC %rot);

                 // set the recharge rate right away
                 if(%deplObj.getDatablock().rechargeRate)
                     %deplObj.setRechargeRate(%deplObj.getDatablock().rechargeRate);

                 // set team, owner, and handle
                 %deplObj.team = %team;
                 %deplObj.owner = 0; // server owns it for now

                 // set the sensor group if it needs one
                 if(%deplObj.getTarget() != -1)
                       setTargetSensorGroup(%deplObj.getTarget(), %team);

                 // place the deployable in the MissionCleanup/Deployables group (AI reasons)
                 addToDeployGroup(%deplObj);

                 //let the AI know as well...
                 AIDeployObject(0, %deplObj);

                 // increment the team count for this deployed object
                 $TeamDeployedCount[%team, %item]++;
                 
                 %deplObj.deploy();
             }
         }
         %file.delete();
}

function serverCmdSaveEquipment(%obj, %num)
{
         // Write out the deployables to a script file
         // for later use
         
         // get the team
         %team = %obj.getSensorGroup();
         
         new fileObject( "saveFile" );
         %filename = "Team" @ %team @ $CurrentMission @ %num @ ".cs";
         saveFile.openForWrite("prefs/" @ %filename);
         
         %depCount = 0;
         %depGroup = nameToID("MissionCleanup/Deployables");
         if (%depGroup > 0)
            %depCount = %depGroup.getCount();
         else
             return;

         // loop through objects
         %savecount = 0;
         for(%x = 0; %x < %depCount; %x++)
         {
                %depObj = %depGroup.getObject(%x);
                %name = %depObj.getDataBlock().getName();
                if(%name $= "DeployedStationInventory" || %name $= "DeployedMotionSensor" ||
                   %name $= "DeployedPulseSensor" || %name $= "TurretDeployedOutdoor" ||
                   %name $= "TurretIndoorDeployable" || %name $= "TurretDeployedFloorIndoor" ||
                   %name $= "TurretDeployedWallIndoor" || %name $= "TurretDeployedCeilingIndoor")
                {
                   if(%depObj.team == %team)
                   {
                       // it's one of ours.
                       // save it
                       saveFile.writeLine("$TKBEquipmentListDataBlockName[" @ %savecount @"] = " @ %name @ ";");
                       saveFile.writeLine("$TKBEquipmentListDataBlockClassName[" @ %savecount @ "] = " @ %depObj.getDataBlock().getClassName() @ ";");
                       saveFile.writeLine("$TKBEquipmentListPos[" @ %savecount @ "] = " @ "\"" @ %depObj.getTransform() @ "\"" @ ";");
                       //saveFile.writeLine("$TKBEquipmentListDeployed[" @ %savecount @ "] = " @ %depObj.getDataBlock().deployed @ ";");
                       //saveFile.writeLine("$TKBEquipmentListDeployedClassName[" @ %savecount @ "] = " @ %depObj.getDataBlock().deployed.className @ ";");
                       %savecount++;
                   }
                }
         }
         
         // save object count
         saveFile.writeLine("$TKBEquipmentListCount = " @ %savecount @ ";");
         saveFile.close();
         saveFile.delete();
}

function serverCmdReturnFlags(%obj, %num)
{
         // resets flags to their starting points
         %flag = $TeamFlag[%num];
         if(%flag)
         {
                  Game.FlagReset(%flag);
         }
}

// default to mortar cam OFF
$MortarCam = false;
function serverCmdMortarCam(%obj, %val)
{
         // turns the mortar cam on or off depending
         // if the client is a super admin
         if(%obj.isSuperAdmin)
         {
             $MortarCam = %val;
         }
}

// default beacon functionality to ON
$AllowBeaconFeatures = true;
function serverCmdBeaconToggle(%obj, %val)
{
         // turns the beacon functionality on/off
         if(%obj.isSuperAdmin)
         {
             $AllowBeaconFeatures = %val;
         }
}

package TKBPractice {
        function loadMission(%missionName,%missionType,%firstMission )
        {
                 // override to reset our variables
                 for(%x = 0; %x < 3; %x++)
                        $BeaconIndex[%x] = 0;
                 parent::loadMission(%missionName,%missionType,%firstMission);
        }
        
        function GameConnection::onConnect( %client, %name, %raceGender, %skin, %voice, %voicePitch )
        {
                 // override to check if they have our local script installed
                 parent::onConnect( %client, %name, %raceGender, %skin, %voice, %voicePitch );
                 schedule(10000, 0, "CommandToClient", %client, 'ValidateScript'); // make them validate
        }
        
        function DefaultGame::clientMissionDropReady(%game, %client)
        {
                 // override to display validation message
                 parent::clientMissionDropReady(%game, %client);
                 ValidateClient(%client);
        }
        
        function MortarImage::onFire(%data,%obj,%slot)
        {
                 // override to give mortar cam ability
                 if($MortarCam)
                     %data.projectile = MortarShotNoShake;
                     
                 %p = Parent::onFire(%data, %obj, %slot);
                 if($MortarCam)
                 {
                      %obj.client.camera.getDataBlock().setMode(%obj.client.camera, "observerFollow", %p);
                      %obj.client.setControlObject(%obj.client.camera);
                 }
        }
        
        function DefaultGame::groupObjectRestore(%game, %this)
        {
           // override because Siege has this but nothing else
           // WE NEED IT TOO BECAUSE RECURSIVE CALLS WITH
           // ERROR MESSAGES SUCK THX.
           for(%i = 0; %i < %this.getCount(); %i++)
                 %this.getObject(%i).objectRestore();
        }

        function DefaultGame::shapeObjectRestore(%game, %object)
        {
                 // same reason as above
                 
                 // This is used for our repair code
                 // the variables are set via the global vars
                 // probably not the greatest but hey... it works
                 %name = %object.getDataBlock().getName();
                 %repair = false;
                 switch$($TKBRepair)
                 {
                     case "BASE":
                          if(%name $= "StationInventory" || %name $= "GeneratorLarge" ||
                          %name $= "SensorMediumPulse" || %name $= "StationVehiclePad" ||
                          %name $= "SensorLargePulse")
                                %repair = true;
                     case "TURRETS":
                           if(%name $= "SentryTurret" || %name $= "TurretBaseLarge")
                                 %repair = true;
                     case "REMOTES":
                           if(%name $= "DeployedStationInventory" || %name $= "DeployedMotionSensor" ||
                           %name $= "DeployedPulseSensor" || %name $= "TurretDeployedOutdoor" ||
                           %name $= "TurretIndoorDeployable" || %name $= "TurretDeployedFloorIndoor" ||
                           %name $= "TurretDeployedWallIndoor" || %name $= "TurretDeployedCeilingIndoor")
                                 %repair = true;
                     case "ALL":
                           %repair = true;
                 }
                 
                 if($TKBTeam != %object.team)
                     %repair = false;
                 
                 if(%repair == true)
                 {
                     if(%object.getDamageLevel())
                     {
                        %object.setDamageLevel(0.0);
                        %object.setDamageState(Enabled);
                     }
                 }
        }
};

activatePackage(TKBPractice);
$Host::Info = "TKBPractice Mod\nAuthor: Lethal_E";
$Host::MOTD = "TKBPractice Mod\nAuthor: Lethal_E\nTrue to the Brew";
