
Fx = class("Fx")

function Fx:new(type, map, x, y, dx, dy)
	local f = instance(self)
	f.type = type
	f.x = x
	f.y = y
	f.dx = dx
	f.dy = dy
	f.time = 0
	f.prg = 0
	if f:def().spriteState then
		local ran = math.random(1, #f:def().spriteNames)
		f.sprite = video.createSpriteState(f:def().spriteNames[ran], "..\\ingameGFX.dat")
	else
		f.var = math.random(1, #f:def().spriteNames)
	end
	f.map = map
	if f:def().getLife then
		f.life = f:def().getLife(f)
	else
		f.life = 1
		print(type, "without llife")
	end
	map:addFx(f)
	return f
end

function Fx:remove()
	if not self._remove then
		self._remove = true
		self.map:removeFx(self)
	end
end

function Fx:def()
	return FX_TYPES[self.type]
end

function Fx:setDelay(d)
	self.delay = d
end

function Fx:update(time)
	if self.delay and self.delay >= 0 then
		self.delay = self.delay - time
		if self.delay <= 0 then
			if self:def().sound then
				self:emitSound(self:def().sound, 1, 1)
			end
			self.delay = nil
		end
	end
	if not self.delay then
		self.x = self.x + self.dx*time
		self.y = self.y + self.dy*time
		self.dx = math.approach(self.dx, 0, math.difference(0,self.dx)*time*self:def().friction)
		self.dy = math.approach(self.dy, 0, math.difference(0,self.dy)*time*self:def().friction)

		self.time = self.time + time
		
		if self.sprite then
			if video.updateSpriteState(self.sprite, time) then
				self:remove()
			end
		end

		if self.life then
			self.prg = math.clamp(self.time/self.life,0,1)

			if self.prg >= 1 then
				self:remove()
			end
		else
			print("no way tot remove effec")
		end

		if self.time > 20 then
			self:remove()
		end

		if self.owner then
			self.x = self.owner.x + math.cos(self.owner.angle + self.ownerAngle)*self.ownerDist
			self.y = self.owner.y + math.sin(self.owner.angle + self.ownerAngle)*self.ownerDist
		end
	end
end

function Fx:emitSound(id, vol, mod)
	if self.map then
		self.map:emitSoundAt(id, self.x, self.y, vol, mod)
	end
end

function Fx:setScale(s)
	self.scale = s
end

function Fx:setOwner(o, oa, od)
	self.owner = o
	self.ownerAngle = oa
	self.ownerDist = od
end

function Fx:setAngle(a)
	self.angle = a
end

function Fx:getRenderRadius()
	return self:def().renderRadius or 512
end

function Fx:renderAt(x,y,scale,angle,a,r,g,b)
	if not self.delay then
		local scale = scale * (self.scale or 1)
		local a = a

		local angle = angle + (self.angle or 0)

		if self:def().getRGB then
			r,g,b = self:def().getRGB(self, self.prg)
		end
		if self:def().getScale then
			scale = scale*self:def().getScale(self, self.prg)
		end
		if self:def().getOpacity then
			a = self:def().getOpacity(self, self.prg)*a
		end
		if self.sprite then
			video.renderSpriteState(self.sprite, x, y, scale, angle, a, r, g, b, self:def().flip)
		else
			video.renderSpriteState(self:def().sprites[self.var], x, y, scale, angle, a, r, g, b, self:def().flip)
		end
	end
end