
if not CLIENT then return end

local POLY = {}
local poly_meta = {__index = POLY}

local function Poly(tab)
	local out_tab = {}
	local x
	
	setmetatable(out_tab, poly_meta)
	
	for _, y in ipairs(tab) do
		if x then
			table.insert(out_tab, {x = x, y = y})
			x = nil
		else
			x = y
		end
	end
	
	return out_tab
end

function POLY:copy()
	return table.Copy(self)
end

function POLY:mul(x, y)
	y = y or x
	
	for _, t in ipairs(self) do
		t.x = t.x * x
		t.y = t.y * y
	end
	
	return self
end

function POLY:mul_ref(x, y, ref_x, ref_y)
	y = y or x
	
	for _, t in ipairs(self) do
		t.x = (t.x - ref_x) * x + ref_x
		t.y = (t.y - ref_y) * y + ref_y
	end
	
	return self
end

function POLY:tra(x, y)
	for _, t in ipairs(self) do
		t.x = t.x + x
		t.y = t.y + y
	end
	
	return self
end

local LIGHT = {}
local light_meta = {__index = LIGHT}

local light_colors = {
	{255, 64, 64},
	{0, 255, 0},
	{64, 64, 255},
	{0, 192, 255},
	{255, 255, 0},
	{255, 0, 255},
	{255, 255, 255},
}
-- light_colors = {{255,127,39},{255,255,42},{24,240,24}}

local function Light()
	local light = {}
	
	setmetatable(light, light_meta)
	
	light:SetColor(unpack(light_colors[math.random(#light_colors)]))
	light:Toggle()
	
	return light
end

function LIGHT:Toggle()
	if math.random(1, 750) == 1 then
		self.state = false
		self.next_toggle = CurTime() + 60*2 + math.random() * 60*5
	else
		self.state = not self.state
		self.next_toggle = CurTime() + 1 + math.random() * 6
	end
end

local variance_on = 0.075
local mult_off = 0.25
function LIGHT:SetColor(r, g, b)
	self.color_on = {
		r = r - r * math.random() * variance_on,
		g = g - g * math.random() * variance_on,
		b = b - b * math.random() * variance_on
	}
	
	self.color_off = {
		r = self.color_on.r * mult_off,
		g = self.color_on.g * mult_off,
		b = self.color_on.b * mult_off
	}
end

function LIGHT:GetColor()
	if self.state then
		return self.color_on.r, self.color_on.g, self.color_on.b, 200
	else
		return self.color_off.r, self.color_off.g, self.color_off.b, 150
	end
end

local LIGHTS = {}
local lights_meta = {}

function lights_meta:__index(k)
	if type(k) == "number" and k > 0 then
		while not rawget(self, k) do
			table.insert(self, Light())
		end
		return self[k]
	else
		return LIGHTS[k]
	end
end

function LIGHTS:Tick()
	local ct = CurTime()
	
	for _, light in ipairs(self) do
		if light.next_toggle < ct then
			light:Toggle()
		end
	end
end

local lightset = {}
setmetatable(lightset, lights_meta)

local poly_light = Poly({
	0.1, 0,
	0.2, 0.15,
	0.25, 0.375,
	0.2, 0.6,
	0.075, 0.94,
	0, 1,
	-0.075, 0.94,
	-0.2, 0.6,
	-0.25, 0.375,
	-0.2, 0.15,
	-0.1, 0,
})

hook.Add("HUDPaint", "XMas Lights", function()
	local w, h = ScrW(), ScrH()
	local s = h/18
	local poly = poly_light:copy():mul(s)
	local i = 1
	
	lightset:Tick()
	
	draw.NoTexture()
	
	for x = s/2, w, s do
		local light = lightset[i]
		
		surface.SetDrawColor(light:GetColor())
		surface.DrawPoly(poly:copy():tra(x, 0))
		
		i = i + 1
	end
end)
