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

fire_timeout = 5;
angle_coeff = 0.08; -- 15 degree

function Initialize()
	BasicInit();
	V2Init();
	local a = object.desc.Armament;
	local turret_index = a.Guns[0].Turret;
	if turret_index >= 0 then
		local turret = a.Turrets[turret_index];
		local left = turret.TurnLeftAngle / 180;
		local right = turret.TurnRightAngle / 180;
		if angle_coeff < left then angle_coeff = left end;
		if angle_coeff < right then angle_coeff = right end;
	end
	angle_coeff = angle_coeff * 0.9;
	if angle_coeff > 0.87 then angle_coeff = 1.1 end;
end

function Main()
	AIparts:Run();
end

function Fire()
	if hold_fire or not unit.IsGunIdle() or unit.GetAmmo1() <= 0 then return end
	local best_target;
	local best_value = 0;
	local enemies = unit.GetEnemyList(0, object.desc.AlarmRange);

	for _,target in pairs(enemies) do
		local target_angle = unit.GetMoveAngle(target);
		if target_angle < angle_coeff then
			local target_type = object.GetTargetType(target);
			local target_dist = unit.GetTargetDistance(target);
			local target_cost = object.desc.Armament.TargetPriorities[target_type] / target_dist * (1 - target_angle);

			if target_cost > best_value then
				best_value = target_cost;
				best_target = target;
			end
		end
	end

	if best_target then 
--		local target_pos = object.GetPosition(best_target);
--		CreateObject("Effects/selected.dsc", target_pos);
		unit.AttackObject(best_target);
	end
end
