------------------------- weaponlib v1 - (c) 2011 xerpi -------------------------

weapon={}


function weapon.create(img,vel,tiempo)

weaponobj = {img = img, w = img:width(), h = img:height(), tim = tiempo, tim_act = timer.new(), bullets={},vel = vel , status = "stop"}

return weaponobj
end

function weapon.blit(obj,deadcolision,yourx,youry,yourw,yourh)
	for i = 1, #obj.bullets do
		if obj.bullets[i].status == "dead" then continue end
		if obj.bullets[i].status == "alive" then
			if not yourx and not youry and not yourw and not yourh then
				if obj.bullets[i].dir == "up" then obj.bullets[i].y = obj.bullets[i].y - obj.vel;
				elseif obj.bullets[i].dir == "down" then obj.bullets[i].y = obj.bullets[i].y + obj.vel; obj.img:rotate(180)
				elseif obj.bullets[i].dir == "right" then obj.bullets[i].x = obj.bullets[i].x + obj.vel; obj.img:rotate(90)
				elseif obj.bullets[i].dir == "left" then obj.bullets[i].x = obj.bullets[i].x - obj.vel obj.img:rotate(-90) end	
				obj.img:blit(obj.bullets[i].x,obj.bullets[i].y)
				if obj.bullets[i].y+obj.h < 0 or obj.bullets[i].y  >272 or obj.bullets[i].x+obj.w < 0 or obj.bullets[i].x >480 then
					obj.bullets[i].status = "dead"
				end	
				obj.img:reset()		
			else
				if yourx and youry and yourw and yourh then
					if obj.bullets[i].dir == "up" or obj.bullets[i].dir == "down" then
						if obj.bullets[i].x + obj.w >= yourx and  obj.bullets[i].x <= yourx+yourw and 
						   obj.bullets[i].y + obj.h >= youry and  obj.bullets[i].y <= youry+yourh then
								if deadcolision then obj.bullets[i].status = "dead" end
						 		return true								
						end	
					elseif obj.bullets[i].dir == "right" or obj.bullets[i].dir == "left" then
						if obj.bullets[i].x + obj.h >= yourx and  obj.bullets[i].x <= yourx+yourw and 
						   obj.bullets[i].y + obj.w >= youry and obj.bullets[i].y <= youry+yourh then
								if deadcolision then obj.bullets[i].status = "dead" end						   
								return true
						end	
					end
				end	
			end
		end
	end
end


function weapon.shoot(obj,x,y,dir,sonido)
	if obj.status == "stop" then obj.status = "run" obj.tim_act:start() end
	if obj.status == "run" then
		if obj.tim_act:time() >= obj.tim then
			if sonido then sonido:play() end
			table.insert(obj.bullets,{x=x,y=y,dir=dir,status="alive"})
			obj.tim_act:reset()
		end
	end
end

function weapon.action(obj,action)
	if action == "start" then obj.status = "run" obj.tim_act:start() end
	if action == "stop" then obj.status = "stop" obj.tim_act:reset() obj.tim_act:stop() end
end
