//////////////////////////////////////////////////////////////////////////
//
// 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 "wraithRush.h"
#include "../units/army.h"
#include "../Iron.h"

namespace { auto & bw = Broodwar; }




namespace iron
{


//////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                          //
//                                  class WraithRush
//                                                                                          //
//////////////////////////////////////////////////////////////////////////////////////////////


WraithRush::WraithRush()
{
}


string WraithRush::StateDescription() const
{
	if (!m_detected) return "-";
	if (m_detected) return "detected";

	return "-";
}


bool WraithRush::Detection() const
{
	const HisBuilding * pHisStarport = nullptr;
	for (const auto & b : him().Buildings())
		if (b->Is(Terran_Starport))
			if (pHisStarport) return true;	// he's got 2 Starports;
			else pHisStarport = b.get();

	if (pHisStarport)
	{
		const MyBuilding * pMyStarport = me().Buildings(Terran_Starport).empty() ? nullptr : me().Buildings(Terran_Starport).front().get();

		if (!pMyStarport ||
			pHisStarport->Completed() && !pMyStarport->Completed() ||
			!pHisStarport->InFog() && (pHisStarport->RemainingBuildTime() < pMyStarport->RemainingBuildTime()))
			return true;
	}

	int hisWraiths = count_if(him().UnitTrace().begin(), him().UnitTrace().end(), [](const pair<Unit, HisUnitTrace> & p)
					{ return p.second.Type() == Terran_Wraith; });

	if (hisWraiths > me().CompletedUnits(Terran_Wraith))
		return true;

	return false;
}


void WraithRush::OnFrame_v()
{
	if ((him().Race() == Races::Protoss) || (him().Race() == Races::Zerg)) return Abort();

	if (me().CompletedBuildings(Terran_Armory) >= 1) return Abort();

	if (m_detected)
	{
		static frame_t lastCancel = 0;
		if (ai()->Frame() - lastCancel > 3*bw->getRemainingLatencyFrames())
		for (const auto & b : me().Buildings(Terran_Starport))
			if (b->Unit()->isTraining())
				if (b->CanAcceptCommand())
				{
				///	bw << "CancelTrain Wraith" << endl;
				///	ai()->SetDelay(5000);
					lastCancel = ai()->Frame();
					return b->CancelTrain();
				}
	}
	else
	{
		if (me().CreationCount(Terran_Wraith) >= 3) return Abort();

		if (Detection())
		{
		///	ai()->SetDelay(100);
			m_detected = true;
			return;
		}
	}
}


} // namespace iron



