NUiCountdown = {}

function NUiCountdown:SetupUI()
	require("nui-hud")
	self.Active = false
	self.Font = nil
	self.DigitTextures = nil
	self:ParseConfig("nui-hud.tbl")
end

function NUiCountdown:ParseConfig(file)
	NUi:ParseGeneralSettings(file, self)
	NUi:ParseConfigSection(file, "#Countdown Settings", function() self:ConfigCountdown() end)
end

function NUiCountdown:ConfigCountdown()
	local t = { Colors = {} }

	local origin = {0.0, 0.0}
	local offset = {1250, -10}

	if parse.optionalString("$Position:") then
		if parse.optionalString("+Origin:") then
			origin = NUi:GetCSV(parse.getString())
		end
		if parse.optionalString("+Offset:") then
			local csv = NUi:GetCSV(parse.getString())
			offset = {csv[1] * self.ScaleFactor, csv[2] * self.ScaleFactor}
		end
	end
	t.Position = NUi:CalculatePosition(origin, offset)

	if parse.optionalString("$Text Color:") then
		local rgba = NUi:GetCSV(parse.getString())
		t.Colors.Text = {rgba[1], rgba[2], rgba[3], rgba[4] or 255}
	else
		t.Colors.Text = {192, 0, 0, 255}
	end

	if parse.optionalString("$Font Scale:") then
		t.FontScale = parse.getFloat() * self.ScaleFactor
	else
		t.FontScale = self.ScaleFactor
	end

	parse.requiredString("#End")
	self.CountdownConfig = t
	self.Active = true
end

function NUiCountdown:InitTextures()
	if not self.Font then
		for i = 1, #gr.Fonts do
			if gr.Fonts[i].Name == "CommChatLarge" then
				self.Font = gr.Fonts[i]
				break
			end
		end
		if not self.Font then return end
	end

	gr.CurrentFont = self.Font
	self.DigitTextures = {}
	local maxDigitW = 0

	for _, c in ipairs({"0","1","2","3","4","5","6","7","8","9",":",".","-"}) do
		local tw = gr.getStringWidth(c)
		local th = self.Font.Height
		local pad = th
		local tex = gr.createTexture(tw + pad*2, th + pad*2, TEXTURE_STATIC)
		gr.CurrentRenderTarget = tex
		gr.setColor(0, 0, 0, 255)
		gr.drawRectangle(0, 0, tw + pad*2, th + pad*2, true)
		gr.setColor(255, 255, 255, 255)
		gr.CurrentFont = self.Font
		gr.drawString(c, pad, pad)
		gr.CurrentRenderTarget = nil
		tex:destroyRenderTarget()
		self.DigitTextures[c] = { tex = tex, tw = tw, th = th, pad = pad }
		if c >= "0" and c <= "9" and tw > maxDigitW then
			maxDigitW = tw
		end
	end

	local fs = self.CountdownConfig and self.CountdownConfig.FontScale or 1.0
	self.FontScale = fs
	self.SlotW  = maxDigitW * fs
	self.ColonW = self.DigitTextures[":"].tw * fs
	self.DotW   = self.DigitTextures["."].tw * fs
	self.SignW  = self.DigitTextures["-"].tw * fs
end

function NUiCountdown:DrawChar(c, slotW, x, y)
	local ne = self.DigitTextures[c]
	if not ne then return end
	local fs = self.FontScale
	local sw, sh, sp = ne.tw * fs, ne.th * fs, ne.pad * fs
	local cx = x + slotW / 2
	gr.drawImage(ne.tex, cx - sw/2 - sp, y - sp, cx + sw/2 + sp, y + sh + sp, 0, 0, 1, 1, 1, true, 0)
end

function NUiCountdown:Draw(currentTime)
	if not self.Active or not self.CountdownConfig then return end

	if not self.Font then
		for i = 1, #gr.Fonts do
			if gr.Fonts[i].Name == "CommChatLarge" then
				self.Font = gr.Fonts[i]
				break
			end
		end
		if not self.Font then return end
	end

	if not self.DigitTextures then
		self:InitTextures()
		if not self.DigitTextures then return end
	end

	local isNeg = currentTime < 0
	local t = math.abs(currentTime)
	local m  = math.floor(t / 60) % 60
	local s  = math.floor(t) % 60
	local cs = math.floor((t % 1) * 100)

	local slotW  = self.SlotW
	local colonW = self.ColonW
	local dotW   = self.DotW
	local signW  = self.SignW
	local totalW = signW + slotW*2 + colonW + slotW*2 + dotW + slotW*2

	local cc  = self.CountdownConfig.Colors.Text
	local pos = self.CountdownConfig.Position
	local x = pos.x - totalW / 2
	local y = pos.y

	gr.setColor(cc[1], cc[2], cc[3], cc[4])

	if isNeg then self:DrawChar("-", signW, x, y) end
	x = x + signW

	self:DrawChar(tostring(math.floor(m / 10)), slotW, x, y) x = x + slotW
	self:DrawChar(tostring(m % 10),             slotW, x, y) x = x + slotW
	self:DrawChar(":",                           colonW, x, y) x = x + colonW
	self:DrawChar(tostring(math.floor(s / 10)), slotW, x, y) x = x + slotW
	self:DrawChar(tostring(s % 10),             slotW, x, y) x = x + slotW
	self:DrawChar(".",                           dotW,   x, y) x = x + dotW
	self:DrawChar(tostring(math.floor(cs / 10)), slotW, x, y) x = x + slotW
	self:DrawChar(tostring(cs % 10),             slotW, x, y)
end

function NUiCountdown:Cleanup()
	if self.DigitTextures then
		for _, entry in pairs(self.DigitTextures) do
			entry.tex:unload()
		end
	end
	self.Active = false
	self.Font = nil
	self.DigitTextures = nil
	self.FontScale = nil
	self.SlotW = nil
	self.ColonW = nil
	self.DotW = nil
	self.SignW = nil
	self.CountdownConfig = nil
end
