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

boxes = { }
supply_timeout = 100;

function Initialize()
	boxes[1] = utils.AssignFrames("boxes_01");
	boxes[2] = utils.AssignFrames("boxes_02"); 
	boxes[3] = utils.AssignFrames("boxes_03");
	boxes[4] = utils.AssignFrames("boxes_04");

	init_ammo = object.GetAmmo();
	prev_state = ammo;
	state = ammo;
	BasicInit();
	V2Init();
	AIparts:AddPeriodic("Supply", supply_timeout, Supply, object.RandomInt(supply_timeout));
end

function CheckDamage(Damage, Point)
	local health = object.GetHealth() - Damage;
	if health < 0 then health = 0 end
	object.SetHealth(health);

	if health <= 0 then
		for _,v in pairs(frames) do
			object.SetGroupDamage(1, v.active);
		end
		if object.GetAmmo() > 0 then
			draw_ammo_boxes(0);

			body.frame.active = body.frame.destroyed
			object.SetGroupVisible(false, body.frame.normal);
			object.SetGroupVisible(true, body.frame.active);
			object.SetGroupDamage(1, body.frame.active);
		end
		object.Die();
	end
end

function draw_ammo_boxes(ammo)
 if ammo > 0 then object.SetGroupVisible(true, boxes[1]) else object.SetGroupVisible(false, boxes[1]) end
 if ammo > init_ammo * 0.25 then object.SetGroupVisible(true, boxes[2]) else object.SetGroupVisible(false, boxes[2]) end
 if ammo > init_ammo * 0.5 then	object.SetGroupVisible(true, boxes[3]) else object.SetGroupVisible(false, boxes[3]) end
 if ammo > init_ammo * 0.75 then object.SetGroupVisible(true, boxes[4]) else object.SetGroupVisible(false, boxes[4]) end
end

function Main()
	AIparts:Run();
	state = object.GetAmmo();
	if state ~= prev_state then draw_ammo_boxes(state) end
	prev_state = object.GetAmmo();
end

function Supply()
	local best_target;
	local best_value = 0;
	local me = object.GetObjectId();
	local position = object.GetPosition();
	for _,target in pairs(unit.GetAllyList(0, object.desc.AlarmRange)) do
		if object.GetObjectId(target) ~= me and unit.NeedAmmo(target, 60) then
			local target_distance = CalcDistance(position, object.GetPosition(target));
			local target_cost = 1 / target_distance;
			if best_value < target_cost 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.Supply(best_target);
	end
end

function Debug()
	ScreenLog("Counter: " .. AIparts.periodic.Supply.counter);
	ScreenWarning("Ammo " ..unit.GetAmmo());
end
