Light = {}
LoadedObjects.Lights = {}

function Light:new(x,y,data)
	local o = {}
	o.pos = {
		x = x,
		y = y
	}
	o.radius = data.radius
	o.shine_radius = data.shine_radius or 0
	o.lum = data.lum or 1
	o.color = data.color or {1,1,1}
	o.flicker_amount = data.flicker or 2
	o.flicker_value = 0
	o.dim = 0
	o.flicker_time = 60/12
	o.flicker_timer = 0

	table.insert(LoadedObjects.Lights,o)
	o.id = #LoadedObjects.Lights

	setmetatable(o, self)
	self.__index = self
	return o
end

function Light:kill()
	if self.id ~= nil then
		table.remove(LoadedObjects.Lights,self.id)
		for _, e in pairs(LoadedObjects.Lights) do
			if e.id > self.id then
				e.id = e.id - 1
			end
		end
	end
	self = nil
end

function Light:flicker()
	self.flicker_timer = self.flicker_timer + 1

	if self.flicker_timer >= self.flicker_time then
		self.flicker_timer = self.flicker_timer - self.flicker_time
		self.flicker_value = math.random(0,1)
		self.flicker_value = math.min(math.max(self.flicker_value, -self.flicker_amount), self.flicker_amount)
	end
end

function Light:drawClear()
	if self.radius ~= 0 then
		local position = {
			x = (self.pos.x - Camera.pos.x) / game.scale,
			y = (self.pos.y - Camera.pos.y) / game.scale
		}
		local radius = (self.radius + self.flicker_value) / game.scale
		love.graphics.circle(
				"fill",
				position.x,
				position.y,
				radius
			)
	end
end

function Light:drawShine()
	if self.radius ~= 0 then
		love.graphics.setColor(self.color[1],self.color[2],self.color[3],1)

		shader.circle_gradient:send("pos_x",- Camera.pos.x + self.pos.x)
		shader.circle_gradient:send("pos_y",- Camera.pos.y + self.pos.y)
		shader.circle_gradient:send("radius",self.shine_radius)
		shader.circle_gradient:send("scale",game.scale)

		love.graphics.setShader(shader.circle_gradient)
		love.graphics.circle(
			"fill",
			- Camera.pos.x + self.pos.x,
			- Camera.pos.y + self.pos.y,
			self.radius
		)
		love.graphics.setShader()
	end
end
