# * * ************************************** * *
# *   ****** Demonstration input file ******   *
# *   ******      UNCLASSIFIED        ******   *
# * * ************************************** * *

# --------------------------------------------------------------
#                         Common Script Methods
# --------------------------------------------------------------

script_interface

  listing on
  debug_writes on

  script_variables
    Array<string> mCategories = Array<string>();
    mCategories.PushBack("fighter");
    mCategories.PushBack("bomber");
    mCategories.PushBack("jammer");
    mCategories.PushBack("uav");
    mCategories.PushBack("awacs");
    mCategories.PushBack("ship");
    mCategories.PushBack("sam");
    mCategories.PushBack("missile");
  end_script_variables


  script string DeterminePlatformCategory(WsfPlatform aPlatform)
    if( aPlatform.IsValid() )
    {
      foreach( string aCategory in mCategories )
      {
        if( aPlatform.CategoryMemberOf( aCategory ) )
        {
          return aCategory;
        }
      }
    }
    return "unknown";
  end_script

   script string DetermineTrackCategory(WsfTrack aTrack)
      if (!aTrack.IsValid())
      {
         return "unknown";
      }

      int ind = aTrack.TargetIndex();
      WsfPlatform plat;
      plat = PLATFORM.FindPlatform( ind );

      if (!plat.IsValid())
      {
         return "unknown";
      }

      string cat = DeterminePlatformCategory( plat );
      return cat;
   end_script

   script bool TestPlatformCategory(WsfPlatform aPlatform, string aCategory)
      if (!aPlatform.IsValid())
      {
         return (aCategory == "unknown");
      }
      else if( aPlatform.CategoryMemberOf( aCategory ) )
      {
         return true;
      }
      else if (aCategory == DeterminePlatformCategory(aPlatform))
      {
         return true;
      }

      return false;
   end_script

   script bool TestTrackCategory(WsfTrack aTrack, string aCategory)
      if (!aTrack.IsValid())
      {
         // "unknown" returns true when aTrack is invalid
         return (aCategory == "unknown");
      }

      int ind = aTrack.TargetIndex();
      WsfPlatform plat;
      plat = PLATFORM.FindPlatform(ind);

      if (!plat.IsValid())
      {
         // "unknown" returns true when aTrack is invalid
         return (aCategory == "unknown");
      }

      bool match = TestPlatformCategory(plat, aCategory);
      return match;
   end_script


   // converts the actual groundRange into an effectiveRange that indicates "how far" aPlatform and aTrack
   // are from each other given their closing speed and the thrust duration of the missle
   // VERY HACKY
   script double EffectiveRange (WsfPlatform aPlatform, WsfTrack aTarget)
      double groundRange         = aPlatform.GroundRangeTo(aTarget);
      double closingSpeed        = aPlatform.ClosingSpeedOf(aTarget);
      double relativeAltitudeMod = aPlatform.RelativeAltitudeOf(aTarget) * 2;

      // mach 3 = 1 020.87 meters / second
      double closingSpeedMod      = ((closingSpeed / 2 + 1520) / 1520);
      double effectiveRange      = (groundRange + (relativeAltitudeMod)) / closingSpeedMod;

      writeln_d("    ", effectiveRange, " (effectiveRange) == ", groundRange, " ((groundRange) + ", relativeAltitudeMod, " (relativeAltitudeMod)) / ", closingSpeedMod, " (speedThrustMod), closingSpeed: ", closingSpeed);

      return effectiveRange;
   end_script

   /*
    *  bool LaunchWeapon ()
    *
    *       Launch a missile at the tracked target.
    */

   script bool LaunchWeapon (WsfPlatform aPlatform, WsfTrack aTarget, WsfWeapon aWeapon)
       bool launched = false;

       if (!aTarget.IsValid() || !aWeapon.IsValid())
       {
          writeln("!!! LaunchWeapon(): Invalid aWeapon or aTarget");
          return launched;
       }

       // We can select the weapon only if it exists, has enough rounds and is not already busy launching
       // (i.e.: it doesn't currently have a task assigned to it...)
       if (aWeapon.IsTurnedOn() && (aWeapon.QuantityRemaining() >= 1 ))
       {
          writeln_d("    Attempting launch at ", aTarget.TargetName());
          launched = aWeapon.FireSalvo(aTarget, 1);
       }

       return launched;
   end_script


   script int GetWeaponNumberActiveMax( string weaponName, Array<Map<string, Object>> aWeaponArray )
      foreach (Map<string, Object> curWeapon in aWeaponArray)
      {
        if( (string)curWeapon["name"] == weaponName )
        {
          if( curWeapon.Exists("numActiveMax") )
          {
            return (int)curWeapon["numActiveMax"];
          }
        }
      }
      return 1;
   end_script


   // return the name of the first weapon from aWeaponArray that can hit aTarget
   script string GetBestWeapon(WsfPlatform aPlatform, WsfTrack aTarget, Array<Map<string, Object>> aWeaponArray, double aLaunchRangeMaxFraction)
      double desiredRange = EffectiveRange(aPlatform, aTarget);

      foreach (Map<string, Object> curWeapon in aWeaponArray)
      {
         if (((WsfWeapon)curWeapon["weapon"]).QuantityRemaining() <= 0)
         {
            continue;
         }
         if ((double)curWeapon["rangeMin"] > desiredRange)
         {
            continue;
         }
         if ((double)curWeapon["rangeMax"] * aLaunchRangeMaxFraction < desiredRange)
         {
            continue;
         }
         return (string)curWeapon["name"];
      }
      return "";
   end_script

   // return the range of the longest-ranged weapon with ammo remaining
   script double GetWeaponRangeMax(WsfPlatform aPlatform, Array<Map<string, Object>> aWeaponArray)
      double rangeMax = 0;

      foreach (Map<string, Object> curWeapon in aWeaponArray)
      {
         if (((WsfWeapon)curWeapon["weapon"]).QuantityRemaining() <= 0)
         {
            continue;
         }
         if ((double)curWeapon["rangeMax"] > rangeMax)
         {
            rangeMax = (double)curWeapon["rangeMax"];
         }
      }
      return rangeMax;
   end_script

   // return the range of the weapon with smallest min range and with ammo remaining
   script double GetWeaponRangeMin(WsfPlatform aPlatform, Array<Map<string, Object>> aWeaponArray)
      double rangeMin = 99999999999.0;

      foreach (Map<string, Object> curWeapon in aWeaponArray)
      {
         if (((WsfWeapon)curWeapon["weapon"]).QuantityRemaining() <= 0)
         {
            continue;
         }
         if ((double)curWeapon["rangeMin"] < rangeMin)
         {
            rangeMin = (double)curWeapon["rangeMin"];
         }
      }
      return rangeMin;
   end_script

   // return the amount of ammo remaining for the weapon with the most ammo
   script double GetWeaponQuantityRemainingMax(WsfPlatform aPlatform, Array<Map<string, Object>> aWeaponArray)
      int quant = 0;

      foreach (Map<string, Object> curWeapon in aWeaponArray)
      {
         if (((WsfWeapon)curWeapon["weapon"]).QuantityRemaining() > quant)
         {
            quant = ((WsfWeapon)curWeapon["weapon"]).QuantityRemaining();
         }
      }
      return quant;
   end_script

   script int GetBucket (double x, double aBucketBase)
    if (x == 0)
    {
       return 0;
    }

    double abs_x = MATH.Fabs(x);

    // convert the log base-10 to a log with the base
    int temp = MATH.Log10(abs_x) / MATH.Log10(aBucketBase);

    // return a negative bucket if our source number is negative
    if (x > 0)
    {
       return temp;
    }
    else
    {
       return -temp;
    }
   end_script

   script WsfTrack GetTrackByName(WsfPlatform aPlatform, string trackName)
      WsfLocalTrackList trackList = aPlatform.MasterTrackList();

      foreach (WsfTrack track in trackList)
      {
        if (track.TargetName() == trackName)
        {
            return track;
        }
      }

      // since we can't return null
      WsfTrack x;
      return x;
   end_script


   // Calculate the relative positioning of aPlatform and aTrack
   script string CalculatePositioning (WsfPlatform aPlatform, WsfTrack aTrack, double aAngleTolerance)
      // Are we heading the same direction?
      bool sameHeading = false;
      bool oppHeading = false;
      bool oppHeadingValid = aTrack.HeadingValid();
      double headingDiff = MATH.Fabs(MATH.NormalizeAngleMinus180_180(aPlatform.Heading() - aTrack.Heading()));

      if (oppHeadingValid && headingDiff < aAngleTolerance)
      {
         sameHeading = true;
      }
      if (oppHeadingValid && headingDiff > (180 - aAngleTolerance))
      {
         oppHeading = true;
      }

      // Is either one of us pointing at the other?
      // Apparently bearing is always valid (?)
      bool pointingMeYou = false;
      bool pointingYouMe = false;

      double pMeYou = MATH.Fabs(aPlatform.RelativeBearingTo(aTrack));
      double pYouMe = MATH.Fabs(aTrack.RelativeBearingTo(aPlatform));

      if (pMeYou < aAngleTolerance)
      {
         pointingMeYou = true;
      }
      if (pYouMe < aAngleTolerance)
      {
         pointingYouMe = true;
      }

      // Put them together and we've got relative positioning
      string positioning = "";
      if (sameHeading && pointingMeYou)
      {
         positioning = "head-to-tail";
      }
      else if (sameHeading && pointingYouMe)
      {
         positioning = "tail-to-head";
      }
      else if (oppHeading && (pointingMeYou || pointingYouMe))
      {
         positioning = "head-to-head";
      }
      else if (pointingMeYou && pointingYouMe)
      {
         positioning = "head-to-head";
      }
      else if (oppHeading)
      {
         positioning = "tail-to-tail";
      }
      else if (pointingMeYou)
      {
         positioning = "me-facing-target";
      }
      else if (pointingYouMe)
      {
         positioning = "target-facing-me";
      }
      else
      {
         positioning = "none";
      }

      // Debug, in case my angle math is bad
//         writeln_d("    ", aPlatform.Name(), " to ", aTrack.TargetName(), ", headingDiff: ", headingDiff, ", pMeYou: ", pMeYou, ", pYouMe: ", pYouMe);
//         writeln_d("    meHeading: ", aPlatform.Heading(), ", youHeading: ", aTrack.Heading());
//         writeln_d("    sameHeading: ", sameHeading, ", oppHeading: ", oppHeading,
//                   ", pointingMeYou: ", pointingMeYou, ", pointingYouMe: ", pointingYouMe,
//                   ", positioning: ", positioning);

      return positioning;
   end_script

   // Calculate a heading to evade all incoming missiles, weighted by distance, and then turn aPlatform to it
   script bool EvadeIncoming(WsfPlatform aPlatform, WsfAIAIProcessor aProc)
      double evadeHeading = 0;
      double evadeDivisor = 0;
      double distMod = 0;
      double bearingMod = 0;

      Array<WsfPlatform> incoming = Array<WsfPlatform>();
      int incomingCount;
      incomingCount = aProc.WeaponsIncoming(incoming);

      if (incomingCount == 0)
      {
         writeln_d ("    no incoming weapons");
         return false;
      }

      double y = 0;
      double x = 0;
      // calculate an average heading to incoming platforms weighted by distance
      for (int i = 0; i < incomingCount; i = i + 1)
      {
         WsfPlatform temp = (WsfPlatform)(incoming[i]);
         if (!temp.IsValid() || temp == aPlatform)
         {
            continue;
         }
         distMod = 1 / (aPlatform.SlantRangeTo(temp));
         bearingMod = MATH.NormalizeAngle0_360(aPlatform.TrueBearingTo(temp));
         x = x + MATH.Sin(bearingMod) * distMod;
         y = y + MATH.Cos(bearingMod) * distMod;

         writeln_d("    Incoming ", temp.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", temp.Latitude(), ", ", temp.Longitude(), ", ", temp.Altitude(), ") @ ", temp.Speed(), "m/s");
         evadeDivisor = evadeDivisor + distMod;
         evadeHeading = evadeHeading + bearingMod * distMod;
      }

      // get the GCI if there is one
      WsfRIPRProcessor aiflProc = aProc.GetRIPRCommanderProcessor();
      WsfRIPRProcessor gciProc = null;
      WsfPlatform      aiflPlat = null;
      WsfPlatform      gciPlat = null;


      if (aiflProc.IsValid())
      {
         gciProc = aiflProc.GetRIPRCommanderProcessor();
         aiflPlat = aiflProc.Platform();
      }
      else
      {
//writeln_d("!!! aiflProc not valid");
      }

      if (gciProc.IsValid())
      {
         gciPlat = gciProc.Platform();
      }
      else
      {
//writeln_d("!!! gciProc not valid");
      }

      // if there's a gci, avoid centroids of all his subs
      if (gciPlat.IsValid())
      {
         foreach (WsfPlatform aifl in gciPlat.Subordinates())
         {
            if (!aifl.IsValid() || aifl == aPlatform || aifl == aiflPlat)
            {
               continue;
            }
            WsfGeoPoint centroid = aifl.GetSubsCentroid();

            if (centroid.X() == 0 && centroid.Y() == 0 && centroid.Z() == 0)
            {
               continue;
            }

//writeln_d("!!! centroid: (", centroid.X(), ", ", centroid.Y(), ", ", centroid.Z(), "), dist: ", (aPlatform.SlantRangeTo(centroid)));
            distMod = 1 / (aPlatform.SlantRangeTo(centroid));
            bearingMod = MATH.NormalizeAngle0_360(aPlatform.TrueBearingTo(centroid));
            x = x + MATH.Sin(bearingMod) * distMod;
            y = y + MATH.Cos(bearingMod) * distMod;

            writeln_d("    AIFL ", aifl.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", centroid.Latitude(), ", ", centroid.Longitude(), ", ", centroid.Altitude(), ")");

            // but we'll avoid peers with less strength than we avoid incoming missiles
            // so let's divide the distMod by 2
            evadeDivisor = evadeDivisor + distMod;
            evadeHeading = evadeHeading + bearingMod * distMod;
         }
      }
      // otherwise, avoid members in your own squadron
      else if (aiflPlat.IsValid())
      {
         foreach (WsfPlatform sub in aiflPlat.Subordinates())
         {
            if (!sub.IsValid() || sub == aPlatform)
            {
               continue;
            }
            distMod = 1 / (aPlatform.SlantRangeTo(sub));
            bearingMod = MATH.NormalizeAngle0_360(aPlatform.TrueBearingTo(sub));
            x = x + MATH.Sin(bearingMod) * distMod;
            y = y + MATH.Cos(bearingMod) * distMod;

            writeln_d("    Peer ", sub.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", sub.Latitude(), ", ", sub.Longitude(), ", ", sub.Altitude(), ") @ ", sub.Speed(), "m/s");

            // but we'll avoid peers with less strength than we avoid incoming missiles
            // so let's divide the distMod by 2
            evadeDivisor = evadeDivisor + distMod;
            evadeHeading = evadeHeading + bearingMod * distMod;
         }
      }

      if (evadeDivisor == 0)
      {
         return false;
      }

//         writeln_d("    evadeHeading: ", evadeHeading, ", evadeDivisor: ", evadeDivisor, ", eH/eD: ", evadeHeading / evadeDivisor, ", x: ", x, ", y: ", y);
//         evadeHeading = evadeHeading / evadeDivisor;
//         evadeHeading = MATH.NormalizeAngle0_360(evadeHeading - 180);

      // correct for quadrant
      double theta = MATH.NormalizeAngle0_360(MATH.ATan(x/y));
      if (y < 0)
      {
         theta = MATH.NormalizeAngle0_360(theta - 180);
      }

      writeln_d("    x: ", x, ", y: ", y, ", theta: ", theta);
      evadeHeading = MATH.NormalizeAngle0_360(theta - 180);

      writeln_d("    Evading incoming at heading ", evadeHeading);
      aPlatform.TurnToHeading(evadeHeading);

      return true;
   end_script

   script bool UpdatePointInterceptLocation (WsfPlatform aPlatform, WsfGeoPoint aPoint)
      double interceptAltitude = aPoint.Altitude();
      double interceptHeading = aPlatform.TrueBearingTo(aPoint);
      double interceptRange = aPlatform.SlantRangeTo(aPoint);

      writeln_d("    T=", TIME_NOW, ", range: ", interceptRange, " true-bearing: ", interceptHeading);

      aPlatform.TurnToHeading(interceptHeading);

      if (MATH.Fabs(interceptAltitude - aPlatform.Altitude()) > 5)
      {
         writeln_d("GoToAltitude: ",interceptAltitude);
         aPlatform.GoToAltitude(interceptAltitude);
      }
      return true;
   end_script

   script bool UpdatePointInterceptLocationWithPathing(WsfPlatform aPlatform, WsfGeoPoint aPoint)
      double interceptAltitude = aPoint.Altitude();
      double interceptHeading = aPlatform.TrueBearingTo(aPoint);
      double interceptRange = aPlatform.SlantRangeTo(aPoint);

      writeln_d("    T=", TIME_NOW, ", range: ", interceptRange, " true-bearing: ", interceptHeading);

      WsfGeoPoint startGeoPoint = aPlatform.Location();
      aPlatform.FindAndSetPath(startGeoPoint, aPoint);

      if (MATH.Fabs (interceptAltitude - aPlatform.Altitude()) > 5)
      {
         writeln_d("GoToAltitude: ",interceptAltitude);
         aPlatform.GoToAltitude(interceptAltitude);
      }
      return true;
   end_script

   // Attempt to maximize our distance from aTarget at the time of weapon detonation
   script double MaximizeFPole(WsfPlatform aPlatform, WsfTrack aTarget, double aFPoleAngle)
      writeln_d("    f-pole on: ", aTarget.TargetName());
      double allowedError = 5.0; // allow for this many degrees of error

      // Normalize within +/-180 so absolute value calculations make sense
      double relativeBearing = aPlatform.RelativeBearingTo(aTarget);
      //writeln_d("--- relative bearing: ", relativeBearing);

      // lean in the direction we're closest to already satisfying
      double desiredBearing = aFPoleAngle;
      if (relativeBearing > 0)
      {
         desiredBearing = desiredBearing * (double) -1.0;
      }
      //writeln_d("--- desired bearing: ", desiredBearing);

      // calculate the difference between our desired and current bearings
      double currentError = MATH.Fabs(MATH.NormalizeAngleMinus180_180(desiredBearing - relativeBearing));
      //writeln_d("--- current error: ", currentError);

      // if we're within the error tolerance, do nothing
      if (currentError <= allowedError)
      {
         return aPlatform.Heading();
      }

      // otherwise, normalize to 0-360 and calculate the change in bearing required
      double fPoleHeading = MATH.NormalizeAngle0_360(aPlatform.TrueBearingTo(aTarget) + desiredBearing);
      //writeln_d("--- f-pole heading: ", fPoleHeading);

      // do the turn
      return fPoleHeading;
//         aPlatform.TurnToHeading(fPoleHeading);
   end_script

end_script_interface
