include("shared.lua")

local offsetX, offsetY = -140, 125

function ENT:Initialize()
	// Lets sort the fuel table only once so we dont need do redo it all the time in update
	self.FuelTableSorted = {}
	table.CopyFromTo(zrush.Fuel, self.FuelTableSorted)
	table.sort(self.FuelTableSorted, function(a, b)
		return a.price > b.price
	end)
end

local localPly
function ENT:DrawTranslucent()
	localPly = localPly or LocalPlayer()

	if zrush.f.DrawUI() and zrush.f.InDistance(localPly:EyePos(), self:GetPos(), 150) then
		self:DrawInfo()
	end
end

function ENT:Draw()
	self:DrawModel()
end

function ENT:DrawInfo()
	localPly = localPly or LocalPlayer()

	cam.Start3D2D(self:LocalToWorld(Vector(0, 0, 85 + 1 * math.abs(math.sin(CurTime()) * 1))), Angle(0, EyeAngles().y - 90, 90), 0.05)

		local y_offset = !table.IsEmpty(zrush.config.Jobs) and zrush.config.Jobs[localPly:Team()] and 0 or 120
		// Title
		draw.SimpleTextOutlined(zrush.language.NPC["FuelBuyer"], "zrush_npc_font01", 0, y_offset + -10, zrush.default_colors["white01"], TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)

		if y_offset == 0 then
			// Profit
			draw.RoundedBox(16, -300, 50, 600, 60, zrush.default_colors["black02"])
			local progress = (1 / zrush.config.FuelBuyer.MaxBuyRate) * zrush.PriceMult
			local pColor = zrush.f.LerpColor(progress, zrush.default_colors["red04"], zrush.default_colors["green04"])

			local sellProfit = zrush.PriceMult - 100
			if sellProfit > 0 then
				sellProfit = "+ " .. sellProfit
			end
			draw.SimpleText(zrush.language.NPC["Profit"], "zrush_npc_font02", -280, 78, zrush.default_colors["white01"], TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
			draw.SimpleText(sellProfit .. "%", "zrush_npc_font02", 280, 78, pColor, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)

			// Fuel Info
			draw.RoundedBox(16, -300, 120, 150, 35 + (30 * table.Count(zrush.Fuel)), zrush.default_colors["black02"])
			draw.SimpleText(zrush.config.Currency .. " / " .. zrush.config.UoM, "zrush_npc_font03", -265, 135, zrush.default_colors["white01"], TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)

			if self.FuelTableSorted then
				for k, v in pairs(self.FuelTableSorted) do
					self:DrawResourceItem(v, -150, 30 * k, 20)
				end
			end
		end

	cam.End3D2D()
end

function ENT:DrawResourceItem(fuelData, xpos, ypos, size)

	local price = math.Round(fuelData.price * (zrush.PriceMult / 100))

	surface.SetDrawColor(fuelData.color)
	surface.SetMaterial(zrush.default_materials["barrel_icon"])
	surface.DrawTexturedRect(xpos + offsetX, ypos + offsetY, size, size)

	draw.DrawText(zrush.config.Currency .. string.Comma(price), "zrush_npc_font03", xpos + offsetX + 25, ypos + offsetY + size * 0.1 - 8, zrush.default_colors["white01"], TEXT_ALIGN_LEFT)
end
