dofile("Scripts/utils.lua");
dofile("Scripts/Init/units.lua");
dofile("Scripts/Init/vehicle2.lua");

fire_timeout = 50;
attack_timeout = 50
shots = 2;
curr_shots = 0;
salvo = false;
attack_position = {0, 0, 0};
salvo_timeout = 900;
deadzone = object.desc.Armament.Guns[0].BallisticDeadZone;

function Main()
	AIparts:Run();
end

function Fire()
	if hold_fire then return end
	local direct = false;
	local best_value = 0;
	local best_distance = 10000;
	local best_target;
	for _,target in pairs(unit.GetEnemyList(0)) do
		local target_type = object.GetTargetType(target);
		local target_cost = object.desc.Armament.TargetPriorities[target_type];
		local target_distance = unit.GetTargetDistance(target);
		if target_distance < deadzone then
			if salvo then
				salvo = false;
				AIparts:RemovePeriodic("AttackObject");
			end
			if target_distance < best_distance then
				best_target = target;
				best_distance = target_distance;
				direct = true;
			end
		elseif not direct then
			if target_cost > best_value then
				best_value = target_cost;
				best_target = target
			end
		end
	end
	if not salvo then
		if best_target then
			if unit.GetTargetDistance(best_target) < deadzone then
				if unit.IsGunIdle() then
--					unit.AttackObject(best_target);
				end
			else
				salvo = true;
				curr_shots = shots;
				attack_position = GetPosition(best_target);
				AIparts:AddPeriodic("AttackObject", attack_timeout, AttackObject);
			end
		end
	end
end

function EndOfSalvo()
	salvo = false;
end

function AttackObject()
	if unit.IsGunIdle() then
		if curr_shots > 0 then
			unit.AttackPlace(attack_position);
			curr_shots = curr_shots - 1;
		else
			AIparts:RemovePeriodic("AttackObject");
			AIparts:AddOneTime("EndOfSalvo", salvo_timeout, EndOfSalvo);
		end
	end
end

function Initialize()
	BasicInit();
	V2Init();
end
