dofile("../defs/attack_defs.lua")

local AttackSystem = inherited("AttackSystem", SystemMap)

function AttackSystem:new()
	local ms = instance(self)
	return ms
end

function AttackSystem:wants(ent)
	return ent.aspects.attack and ent.aspects.angle
end

function AttackSystem:ent_added(ent)
end

function AttackSystem:ent_removed(ent)
end

function AttackSystem:step(dt)
	local world = self.world
	for ent, _ in pairs(self.ents) do
		if ent:can_use_attack() then
			for index, slot in pairs(ent.attack_slots) do
				local delay = slot.delay
				if delay > 0 then

					delay = delay - dt*slot.attack_recovery_speed
					if delay <= 0 then
						slot.delay = 0
					else
						slot.delay = delay
					end
				else
					local adef = slot.attack_def
					adef.step(ent, slot, dt)
					--[[
					local charge = slot.attack_charge
					local max = slot.attack_charge_max
					if max > 0 then
						if charge < max then
							charge = charge + dt*slot.attack_charge_speed
							if charge >= max then
								slot.attack_charge = max
							else
								slot.attack_charge = charge
							end
						end
					end]]

					if slot.intent then
						local max_spinup = slot.attack_spinup
						if max_spinup > 0 and slot.spinup < max_spinup then
							slot.spinup = slot.spinup + dt
							local prg = slot.spinup/max_spinup
							ent:set_feedback("spinup", prg)
							if slot.spinup >= max_spinup then
								slot.spinup = max_spinup
							end
						else							
							adef.execute(ent, slot, dt)
							local delay = slot.attack_recovery_max
							ent:set_attack_delay(index, delay)
							for other_index,other_slot in pairs(ent.attack_slots) do
								local min_delay = math.min(delay, other_slot.attack_recovery_max)
								ent:set_attack_delay(other_index, min_delay)						
							end
							slot.spinup = 0
							break
						end
					end
				end
			end
		end
	end
end

return AttackSystem