include("shared.lua")

local use_font = system.IsWindows() and "Tahoma" or "Verdana"
surface.CreateFont("Farming_SegoeUI_16", {font = "Segoe UI", size = 16, weight = 500, antialias = true})
surface.CreateFont("Farming_SegoeUI_18", {font = "Segoe UI", size = 18, weight = 100, antialias = true})
surface.CreateFont("Farming_SegoeUI_20", {font = "Segoe UI", size = 20, weight = 600, antialias = true})
surface.CreateFont("Farming_SegoeUI_20_NF", {font = "Segoe UI", size = 20, weight = 650, antialias = true})
surface.CreateFont("Farming_HeadInfo", {font = use_font, size = 45, weight = 1000, blursize = 0, scanlines = 0})

local local_ply, dist
local vector_1 = Vector(0, 0, 1)
function ENT:Draw()
	self:DrawModel()
end

function ENT:DrawTranslucent()
	local_ply = local_ply or LocalPlayer()
	dist = local_ply:EyePos():DistToSqr(self:GetPos())
	if dist > 100000 then return end
	local ang = self:GetAngles()	
	local pos = self:GetPos() + (vector_1 * (self:OBBMaxs().z + 5 + math.sin(SysTime() * 2)))
	ang:RotateAroundAxis(ang:Forward(), 90)
	ang:RotateAroundAxis(ang:Right(), -90)
	ang:RotateAroundAxis(ang:Up(), 0)
	cam.Start3D2D(pos, Angle(0, EyeAngles().y - 90, 90), 0.15)
		draw.SimpleTextOutlined(self.PrintName, "Farming_HeadInfo", 0, -50, Color(102, 204, 51, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 102, 0, 255))
	cam.End3D2D()
end

FarmingCFG.LastUpdate = FarmingCFG.LastUpdate or 0
FarmingCFG.Prices = FarmingCFG.Prices or {}
FarmingCFG.SellPrices = FarmingCFG.SellPrices or {}
net.Receive("Farming_SendPriceList", function()
	FarmingCFG.LastUpdate = net.ReadUInt(32)
	FarmingCFG.Prices = net.ReadTable()
	FarmingCFG.SellPrices = net.ReadTable()
end)

local sentences = {
	"Es müssen Samen in ein leeres Beet gesät werden, damit du anfangen kannst, etwas zu ernten.",
	"Wenn eine Pflanze zu lange nicht gewässert wurde, stirbt diese ab und wird wertlos.",
	"Es ist nicht sehr lukrativ, nur Pflanzen einer Art zu halten, weil die Verkaufspreise stark variieren können.",
	"Pflanzen haben eine maximale Kapazität an möglicher Ernte. Sie benötigen aber trotzdem weitere Wässerung.",
	"Du benötigst Verkaufsbehälter um mir Ernte zu verkaufen. Stelle diese vor dem Verkauf einfach in meine Nähe.",
	"Die Verkaufspreise des Markts variieren hin und wieder mal. Wähle deinen Verkaufszeitpunkt gut aus.",
	"Die Hacke wird zum Platzieren von leeren Beeten benutzt. Diese müssen dann mit Samen bebaut werden.",
	"Du kannst nicht mehr als "..FarmingCFG.MaxPlots.." Beete besitzen. Dabei spielt die Art keine Rolle!"
}

local marketmenu
net.Receive("Farming_ShowBuyMenu", function()
	if IsValid(marketmenu) then marketmenu:Close() end
	local npc = net.ReadEntity()
	if !IsValid(npc) then return end
	local Crops = {}
	for k, v in ipairs(FarmingCFG.Crops) do
		table.insert(Crops, {FarmingCFG.SellPrices[k] or 0, v.cropname, v.cropmodel, k})
	end
	local Seeds = {}
	for k, v in ipairs(FarmingCFG.Crops) do
		table.insert(Seeds, {FarmingCFG.Prices[k] or 0, v.seedname, "models/props/eryk/farmingmod/seedbag.mdl", k})
	end
	local ItemTable = {}
	local RoundUps = net.ReadInt(16)
	while RoundUps != -1 do
		for i=1, RoundUps do
			local cnt = net.ReadInt(16)
			local index = ItemTable[cnt]
			ItemTable[cnt] = index and index + net.ReadInt(16) or net.ReadInt(16)
		end
		RoundUps = net.ReadInt(16)
	end
	local TotalSalePrice, SaleAmount = 0, 0
	for i=1, table.maxn(ItemTable) do
		local priceindex = ItemTable[i]
		if priceindex then
			SaleAmount = SaleAmount + 1
			TotalSalePrice = TotalSalePrice + Crops[i][1] * priceindex
		end
	end
	TotalSalePrice = math.floor(TotalSalePrice)
	marketmenu = vgui.Create("DFrame")
	marketmenu:SetTitle("")
	marketmenu:ShowCloseButton(false)
	marketmenu:SetDraggable(false)
	marketmenu:SetSize(720, ScrH() * 0.85)
	marketmenu:Center()
	marketmenu:MakePopup()
	marketmenu:ParentToHUD()
	marketmenu.Close = function(self)
		self:Remove()
	end
	local name = FarmingCFG.NPC_Name
	local sentence = sentences[math.random(#sentences)]
	marketmenu.Paint = function(self, w, h)
		draw.RoundedBoxEx(8, 0, 0, w, 40, Color(47, 54, 76, 255), true, true)
		draw.SimpleText(name.."s Pflanzenmarkt", "Farming_SegoeUI_16", w / 2, 0, color_white, TEXT_ALIGN_CENTER)
		draw.RoundedBoxEx(8, 0, h - 40, w, 40, Color(47, 54, 76, 255), false, false, true, true)
		surface.SetDrawColor(20, 24, 33, 255)
		surface.DrawRect(0, 40, w, h - 80)
		for i = 1, 3 do
			draw.SimpleText(i == 1 and "Verkaufspreise" or i == 2 and "Samen handeln" or "Deine Ware", "Farming_SegoeUI_20", i * 225 - 90, 17, color_white, TEXT_ALIGN_CENTER)
			surface.SetDrawColor(25, 29, 38, 255)
			surface.DrawRect(i * 225 - 195, 40, 210, h - 80)
		end
		draw.SimpleText(name..": "..sentence, "Farming_SegoeUI_18", 360, h - 30, color_white, TEXT_ALIGN_CENTER)
	end
	local ply = LocalPlayer()
	marketmenu.Think = function()
		if !IsValid(npc) or !ply:Alive() or ply:EyePos():DistToSqr(npc:GetPos()) > 62500 then
			marketmenu:Close()
		end
	end
	local exitbtn = vgui.Create("DButton", marketmenu)
	exitbtn:SetSize(22, 22)
	exitbtn:SetFont("Farming_SegoeUI_20")
	exitbtn:SetText("X")
	exitbtn:SetColor(Color(250, 250, 250, 255))
	exitbtn:SetPos(marketmenu:GetWide() - 22, 0)
	exitbtn.Paint = function(self, w)
		draw.RoundedBoxEx(8, 0, 0, w, 40, Color(70, 84, 162, 255), false, true)
	end
	exitbtn.DoClick = function(self)
		surface.PlaySound("ui/buttonclick.wav")
		marketmenu:Close()
	end
	local selllist = vgui.Create("DScrollPanel", marketmenu)
	selllist:SetPos(30, 45)
	selllist:SetSize(210, marketmenu:GetTall() - 90)
	selllist.Paint = function(self, w, h)
	end
	selllist:GetVBar():SetWide(5)
	selllist:GetVBar().Paint = function(s)
		draw.RoundedBox(0, 0, 0, s:GetWide(), s:GetTall(), Color(29, 32, 41))
	end
	selllist:GetVBar().btnGrip.Paint = function(s)
		draw.RoundedBox(0, 0, 1, s:GetWide(), s:GetTall() - 2, Color(59, 62, 71))
	end
	selllist:GetVBar().btnUp.Paint = function(s)
	end
	selllist:GetVBar().btnDown.Paint = function(s)
	end
	local function AddSellableItem(parent, info)
		local info1 = info[1]
		local info2 = info[2]
		local info3 = info[3]
		local panel = vgui.Create("DPanel", parent)
		panel:SetSize(200, 50)
		panel:Dock(TOP)
		panel:DockMargin(0, 0, 0, 2)
		panel.Paint = function(self, w, h)
			surface.SetDrawColor(39, 42, 51, 255)
			surface.DrawRect(0, 0, w, h)
			surface.SetDrawColor(50, 50, 50, 255)
			surface.DrawOutlinedRect(0, 0, w, h)
			draw.SimpleText(info2, "Farming_SegoeUI_16", 5, 0, color_white)
			draw.SimpleText("$"..string.Comma(math.ceil(info1)), "Farming_SegoeUI_20_NF", w - 5, h / 2, color_white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
		end
		local model_icon = vgui.Create("SpawnIcon", panel)
		model_icon:SetModel(info3)
		model_icon:SetPos(10, 16)
		model_icon:SetSize(32, 32)
		model_icon:SetMouseInputEnabled(false)
	end
	for k, v in SortedPairsByMemberValue(Crops, 1) do
		AddSellableItem(selllist, v)
	end
	local buylist = vgui.Create("DScrollPanel", marketmenu)
	buylist:SetPos(255, 45)
	buylist:SetSize(210, marketmenu:GetTall() - 90)
	buylist.Paint = function(self, w, h)
	end
	buylist:GetVBar():SetWide(5)
	buylist:GetVBar().Paint = function(s)
		draw.RoundedBox(0, 0, 0, s:GetWide(), s:GetTall(), Color(29, 32, 41))
	end
	buylist:GetVBar().btnGrip.Paint = function(s)
		draw.RoundedBox(0, 0, 1, s:GetWide(), s:GetTall() - 2, Color(59, 62, 71))
	end
	buylist:GetVBar().btnUp.Paint = function(s)
	end
	buylist:GetVBar().btnDown.Paint = function(s)
	end
	local NextBuy
	local function AddBuyableItem(parent, info, item)
		local info1 = info[1]
		local info2 = info[2]
		local info3 = info[3]
		local panel = vgui.Create("DPanel", parent)
		panel:SetSize(200, 50)
		panel:Dock(TOP)
		panel:DockMargin(0, 0, 0, 2)
		panel.Paint = function(self, w, h)
			surface.SetDrawColor(39, 42, 51, 255)
			surface.DrawRect(0, 0, w, h)
			surface.SetDrawColor(50, 50, 50, 255)
			surface.DrawOutlinedRect(0, 0, w, h)
			draw.SimpleText(info2, "Farming_SegoeUI_16", 5, 0, color_white)
			draw.SimpleText("Preis: $"..string.Comma((info and info1 or "X")), "Farming_SegoeUI_16", w - 5, h * 0.3, color_white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
		end
		local model_icon = vgui.Create("SpawnIcon", panel)
		model_icon:SetModel(info3)
		model_icon:SetPos(10, 16)
		model_icon:SetSize(32, 32)
		model_icon:SetMouseInputEnabled(false)
		local button = vgui.Create("DButton", panel)
		button:SetSize(60, 22)
		button:SetFont("Farming_SegoeUI_16")
		button:SetText("Kaufen")
		button:SetColor(Color(250, 250, 250, 255))
		button:SetPos(panel:GetWide() - button:GetWide() + 7, panel:GetTall() / 2)
		button.Paint = function(self, w, h)
			surface.SetDrawColor(self.Hovered and Color(99, 102, 111, 255) or Color(69, 72, 81, 255))
			surface.DrawRect(0, 0, w, h)
			surface.SetDrawColor(46, 58, 84, 255)
			surface.DrawOutlinedRect(0, 0, w, h)
		end
		button.DoClick = function(self)
			if (NextBuy or 0) > CurTime() then return end
			NextBuy = CurTime() + 1
			net.Start("Farming_Buy")
				net.WriteEntity(npc)
				net.WriteUInt(item, 16)
			net.SendToServer()
		end
	end
	local order = 0
	for k, v in SortedPairsByMemberValue(Seeds, 1) do
		order = order + 1
		AddBuyableItem(buylist, v, v[4])
	end
	local NextThink
	local Created = false
	local SellBtn
	local amt
	exitbtn.Think = function()
		if (NextThink or 0) > CurTime() then return end
		NextThink = CurTime() + 1
		amt = 0
		local wep = ply:GetWeapon("weapon_hoe")
		if wep:IsValid() then
			for k, v in pairs(wep.Seeds) do
				if v > 0 then
					amt = amt + v
				end
			end
		end
		if amt > 0 then
			if Created then return end
			Created = true
			SellBtn = vgui.Create("DButton", buylist)
			SellBtn:SetTall(25)
			SellBtn:Dock(TOP)
			SellBtn:DockMargin(0, 0, 0, 5)
			SellBtn:SetFont("Farming_SegoeUI_16")
			SellBtn:SetText("x"..amt.." Samen verkaufen")
			SellBtn:SetColor(Color(250, 250, 250, 255))
			SellBtn.Paint = function(self, w, h)
				self:SetText("x"..amt.." Samen verkaufen")
				surface.SetDrawColor(self.Hovered and Color(99, 102, 111, 255) or Color(69, 72, 81, 255))
				surface.DrawRect(0, 0, w, h)
				surface.SetDrawColor(46, 58, 84, 255)
				surface.DrawOutlinedRect(0, 0, w, h)
			end
			SellBtn.DoClick = function()
				SellBtn:Remove()
				net.Start("Farming_SellSeeds")
					net.WriteEntity(npc)
				net.SendToServer()
			end
		else
			if Created then
				Created = false
				if IsValid(SellBtn) then
					SellBtn:Remove()
				end
			end
		end
	end
	local playerlist = vgui.Create("DScrollPanel", marketmenu)
	playerlist:SetPos(480, 45)
	playerlist:SetSize(210, marketmenu:GetTall() - 90)
	playerlist.Paint = function(self, w, h)
	end
	playerlist:GetVBar():SetWide(5)
	playerlist:GetVBar().Paint = function(s)
		draw.RoundedBox(0, 0, 0, s:GetWide(), s:GetTall(), Color(29, 32, 41))
	end
	playerlist:GetVBar().btnGrip.Paint = function(s)
		draw.RoundedBox(0, 0, 1, s:GetWide(), s:GetTall() - 2, Color(59, 62, 71))
	end
	playerlist:GetVBar().btnUp.Paint = function(s)
	end
	playerlist:GetVBar().btnDown.Paint = function(s)
	end
	local function AddPlayerItems(parent, num, id)
		local panel = vgui.Create("DPanel", parent)
		panel:SetSize(200, 50)
		panel:Dock(TOP)
		panel:DockMargin(0, 0, 0, 2)
		local plant_id = Crops[id][2]
		panel.Paint = function(self, w, h)
			surface.SetDrawColor(39, 42, 51, 255)
			surface.DrawRect(0, 0, w, h)
			surface.SetDrawColor(50, 50, 50, 255)
			surface.DrawOutlinedRect(0, 0, w, h)
			draw.SimpleText(plant_id, "Farming_SegoeUI_16", 5, 0, color_white)
			draw.SimpleText("x"..num, "Farming_SegoeUI_20", w - 5, h / 2, color_white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER)
		end
		local plantsid3 = Crops[id][3]
		local model_icon = vgui.Create("SpawnIcon", panel)
		model_icon:SetModel(plantsid3)
		model_icon:SetPos(10, 16)
		model_icon:SetSize(32, 32)
		model_icon:SetMouseInputEnabled(false)
	end
	if TotalSalePrice > 0 then
		local amount = 0
		for i=1, table.maxn(ItemTable) do
			local index = ItemTable[i]
			if index then
				amount = amount + 1
				AddPlayerItems(playerlist, index, i)
			end
		end
		local label = vgui.Create("DPanel", playerlist)
		label:SetTall(20)
		label:Dock(TOP)
		label:DockMargin(0, 0, 0, 5)
		label.Paint = function(self, w, h)
			draw.SimpleText("Ware für $"..string.Comma(TotalSalePrice).." verkaufen", "Farming_SegoeUI_20_NF", w / 2, h / 2, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
			surface.SetDrawColor(color_white)
			surface.DrawLine(0, h - 1, w, h - 1)
		end
		local button = vgui.Create("DButton", playerlist)
		button:SetSize(x, 22)
		button:Dock(TOP)
		button:DockMargin(0, 0, 0, 5)
		button:SetFont("Farming_SegoeUI_16")
		button:SetText("Verkaufen")
		button:SetColor(Color(250, 250, 250, 255))
		button.Paint = function(self, w, h)
			surface.SetDrawColor(self.Hovered and Color(99, 102, 111, 255) or Color(69, 72, 81, 255))
			surface.DrawRect(0, 0, w, h)
			surface.SetDrawColor(46, 58, 84, 255)
			surface.DrawOutlinedRect(0, 0, w, h)
		end
		button.DoClick = function(self)
			net.Start("Farming_SellCrops")
				net.WriteEntity(npc)
			net.SendToServer()
			marketmenu:Remove()
		end
	else
		local label = vgui.Create("DPanel", playerlist)
		label:SetTall(60)
		label:Dock(TOP)
		label:DockMargin(0, 0, 0, 5)
		label.Paint = function(self, w, h)
			draw.DrawText("Du hast keine Ware\nzu verkaufen.", "Farming_SegoeUI_20", w / 2, h / 2 - 20, color_white, TEXT_ALIGN_CENTER)
		end
	end
	local label = vgui.Create("DPanel", playerlist)
	label:SetTall(45)
	label:Dock(TOP)
	label:DockMargin(0, 0, 0, 5)
	local changed = false
	label.Paint = function(self, w, h)
		surface.SetDrawColor(Color(59, 62, 71, 255))
		surface.DrawRect(0, 0, w, h)
		surface.SetDrawColor(46, 58, 84, 255)
		surface.DrawOutlinedRect(0, 0, w, h)
		local interval = !changed and math.max(0, FarmingCFG.LastUpdate + FarmingCFG.RandomInterval - CurTime()) or 0
		if interval > 0 then
			draw.DrawText("Nächste Preisänderung in:\n"..string.ToMinutesSeconds(math.max(0, FarmingCFG.LastUpdate + FarmingCFG.RandomInterval - CurTime())), "Farming_SegoeUI_16", w / 2, h / 2 - 15, color_white, TEXT_ALIGN_CENTER)
		else
			changed = true
			draw.DrawText("Die Preise wurden geändert.\nRufe das Menü erneut auf!", "Farming_SegoeUI_16", w / 2, h / 2 - 15, color_white, TEXT_ALIGN_CENTER)
		end
	end
end)