//////////////////////////////////////////////////////////////////////////
//
// This file is part of Iron's source files.
// Iron is free software, licensed under the MIT/X11 License. 
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2016, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////


#include "wraithAttack.h"
#include "../units/factory.h"
#include "../behavior/kiting.h"
#include "../behavior/raiding.h"
#include "strategy.h"
#include "baseDefense.h"
#include "../Iron.h"

namespace { auto & bw = Broodwar; }


namespace iron
{




void wraithAttack()
{
	if (ai()->Frame() % 50 != 0) return;

	vector<MyUnit *> MyWraiths;
	for (const auto & u : me().Units(Terran_Wraith))
		if (u->Completed())
			if (u->GetBehavior()->IsRaiding() ||
				u->GetBehavior()->IsKiting() &&
					( ai()->Frame() - u->GetBehavior()->IsKiting()->LastAttack() > 50 ||
					  ai()->GetStrategy()->Active<BaseDefense>()
					))
				MyWraiths.push_back(u.get());

	if (MyWraiths.empty()) return;

	static frame_t delay = 0;

	multimap<int, HisUnit *> Targets;
	for (const auto & u : him().Units())
		if (!u->InFog())
//			if (u->Chasers().empty())
//			if (u->VChasers().empty())
//			if (u->Destroyers().empty())
			if (!u->AirAttack())
				if (!u->Flying() && u->GroundAttack() ||
					u->Flying())
				{
					int minDistToBase = numeric_limits<int>::max();
					for (VBase * base : me().Bases())
					{
						int d = groundDist(u->Pos(), base->BWEMPart()->Center());
						if (d < minDistToBase)
						{
							minDistToBase = d;
						}
					}

					int score = minDistToBase;
					Targets.emplace(score, u.get());
				}

	if (Targets.empty()) return;

	for (MyUnit * u : MyWraiths)
	{
		u->ChangeBehavior<Raiding>(u, Targets.begin()->second->Pos());
	}

///	ai()->SetDelay(499);
}




} // namespace iron



