#include "stdafx.h"
#include "../../SparAIContainer.h"
#include "../PerceptualState.h"
#include "ResourceManager.h"
#include "../Locations/Static/Autopopulated/BaseLocation.h"

ResourcesSaturation ResourceManager::calculateProbesSaturationRatio() const
{
  size_t nbTotalCrystals = 0;
  size_t nbTotalGeysers = 0;
  size_t nbTotalProbesMinerals = 0;
  size_t nbTotalProbesGas = 0;
  Map* map = Spar->getPerceptualState()->getMap();
  std::pair<Map::base_location_iterator, Map::base_location_iterator> baseLocations = map->getBaseLocations();
  for (Map::base_location_iterator it = baseLocations.first; it != baseLocations.second; ++it)
  {
    const BaseLocation* baseLocation = (*it);
    if (baseLocation->getNbCompletedOwnUnits(BWAPI::UnitTypes::Protoss_Nexus) > 0)
    {
      nbTotalCrystals += baseLocation->getLastKnownNbCrystalsLeft();
      nbTotalProbesMinerals += baseLocation->getNbProbesOnMinerals();
      nbTotalGeysers += baseLocation->getNbGeysers();
      nbTotalProbesGas += baseLocation->getNbProbesOnGas();
    }
  }

  double totalRatio = 0.0;
  if (nbTotalCrystals > 0)
  {
    for (Map::base_location_iterator it = baseLocations.first; it != baseLocations.second; ++it)
    {
      const BaseLocation* baseLocation = *it;
      if (baseLocation->getNbOwnUnits(BWAPI::UnitTypes::Protoss_Nexus) > 0)
      {
        const double saturation = baseLocation->probesMineralsSaturation();
        if (saturation != 0.)
        {
          const double ratio = baseLocation->getNbProbesOnMinerals() / saturation;
          totalRatio += (baseLocation->getLastKnownNbCrystalsLeft() * ratio) / double(nbTotalCrystals);
        }
      }
    }
  }
  return ResourcesSaturation(nbTotalProbesMinerals, nbTotalCrystals, totalRatio,
                    nbTotalProbesGas, nbTotalGeysers);
}