include("shared.lua")

local use_font = system.IsWindows() and "Tahoma" or "Verdana"
surface.CreateFont("Farming_PlantPot", {font = use_font, size = 28, weight = 0, blursize = 0, scanlines = 0, antialias = true})
surface.CreateFont("Farming_Close", {font = use_font, size = 13, weight = 1000})

local PlotMenu
net.Receive("Farming_UsePlot", function(len)
	local Plot = net.ReadEntity()
	local Crops = net.ReadUInt(8)
	if !IsValid(Plot) or !Crops then return end
	if IsValid(PlotMenu) then PlotMenu:Close() end
	local mainsize = 70
	PlotMenu = vgui.Create("DFrame")
	PlotMenu:SetTitle(FarmingAddon.GetPlantName(Plot:GetID()))
	PlotMenu:SetWide(230)
	PlotMenu:ShowCloseButton(false)
	PlotMenu:MakePopup()
	PlotMenu.Paint = function()
		draw.RoundedBox(4, 0, 0, PlotMenu:GetWide(), PlotMenu:GetTall(), Color(45, 45, 45, 255))
	end
	PlotMenu:ParentToHUD()
	local ply = LocalPlayer()
	PlotMenu.Think = function()
		if !IsValid(Plot) or Plot:GetNoDraw() or !ply:Alive() or ply:EyePos():DistToSqr(Plot:GetPos()) > 10000 then
			PlotMenu:Close()
		end
	end
	local Close = vgui.Create("DButton", PlotMenu)
	Close:SetSize(50, 20)
	Close:SetPos(PlotMenu:GetWide() - 52, 2)
	Close:SetText("X")
	Close:SetFont("Farming_Close")
	Close:SetTextColor(color_white)
	Close.Paint = function(self, w, h)
		local col
		if self:IsHovered() then
			col = Color(255, 100, 100)
		else
			col = Color(200, 50, 50)
		end
		draw.RoundedBox(4, 0, 0, w, h, col)
	end
	Close.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		PlotMenu:Remove()
	end
	local time = 40
	if Crops > 0 then
		mainsize = mainsize + 30
		local CollectButton = vgui.Create("DButton", PlotMenu)
		CollectButton:SetPos(10, time)
		CollectButton:SetText(FarmingAddon.GetCropName(Plot:GetID()).." (x"..Crops..") ernten")
		CollectButton:SetSize(210, 20)
		CollectButton.DoClick = function()
			if IsValid(Plot) then
				net.Start("Farming_CollectCrops")
					net.WriteEntity(Plot)
				net.SendToServer()
			end
			if IsValid(PlotMenu) then
				surface.PlaySound("ui/buttonclick.wav")
				PlotMenu:Close()
			end
		end
		time = time + 30
	end
	if Plot:GetID() > 0 then
		mainsize = mainsize + 30
		local DestroyButton = vgui.Create("DButton", PlotMenu)
		DestroyButton:SetPos(10, time)
		DestroyButton:SetText("Feld abbauen")
		DestroyButton:SetSize(210, 20)
		DestroyButton.DoClick = function()
			if !IsValid(Plot) then return end
			surface.PlaySound("ui/buttonclick.wav")
			if IsValid(PlotMenu) then
				PlotMenu:Close()
			end
			local CanDestroy = vgui.Create("DFrame")
			CanDestroy:SetTitle("Bestätigen?")
			CanDestroy:SetSize(260, 85)
			CanDestroy:ShowCloseButton(false)
			CanDestroy:MakePopup()
			CanDestroy.Paint = function(self, w, h)
				draw.RoundedBox(4, 0, 0, w, h, Color(200, 100, 100))
				draw.RoundedBox(4, 1, 1, w - 2, h - 2, Color(45, 45, 45))
			end
			CanDestroy:Center()
			CanDestroy.Think = function()
				if !IsValid(Plot) then
					CanDestroy:Close()
				end
			end
			local Close = vgui.Create("DButton", CanDestroy)
			Close:SetSize(50, 20)
			Close:SetPos(CanDestroy:GetWide() - 52, 2)
			Close:SetText("X")
			Close:SetFont("Farming_Close")
			Close:SetTextColor(color_white)
			Close.Paint = function(self, w, h)
				local col
				if self:IsHovered() then
					col = Color(255, 100, 100)
				else
					col = Color(200, 50, 50)
				end
				draw.RoundedBox(4, 0, 0, w, h, col)
			end
			Close.DoClick = function()
				surface.PlaySound("ui/buttonclick.wav")
				CanDestroy:Remove()
			end
			local Agree_Destroy_Button = vgui.Create("DButton", CanDestroy)
			Agree_Destroy_Button:SetPos(30, 35)
			Agree_Destroy_Button:SetText("Fortfahren")
			Agree_Destroy_Button:SetSize(200, 20)
			Agree_Destroy_Button.DoClick = function()
				if IsValid(Plot) then
					net.Start("Farming_DestroyPlot")
						net.WriteEntity(Plot)
					net.SendToServer()
				end
				if IsValid(CanDestroy) then
					surface.PlaySound("ui/buttonclick.wav")
					CanDestroy:Close()
				end
			end
			local Deny_Destroy_Button = vgui.Create("DButton", CanDestroy)
			Deny_Destroy_Button:SetPos(30, 60)
			Deny_Destroy_Button:SetText("Abbrechen")
			Deny_Destroy_Button:SetSize(200, 20)
			Deny_Destroy_Button.DoClick = function()
				if IsValid(CanDestroy) then
					surface.PlaySound("ui/buttonclick.wav")
					CanDestroy:Close()
				end
			end
			CanDestroy:SetPos(ScrW() / 2 - CanDestroy:GetWide() / 2, ScrH())
			CanDestroy:MoveTo(ScrW() / 2 - CanDestroy:GetWide() / 2, ScrH() / 2 - CanDestroy:GetTall() / 2, 0.25, 0, 0.5)
		end
		time = time + 30
	end
	local allowed, seeds = false, {}
	local wep = ply:GetWeapon("weapon_hoe")
	if wep:IsValid() then
		for k, v in pairs(wep.Seeds) do
			if k != Plot:GetID() and v > 0 then
				seeds[k] = v
				allowed = true
			end
		end
	end
	local PlantButton = vgui.Create("DButton", PlotMenu)
	PlantButton:SetPos(10, time)
	PlantButton:SetText("Anbauen")
	if !allowed then
		PlantButton:SetDisabled(true)
	end
	PlantButton:SetSize(210, 20)
	PlantButton.DoClick = function()
		if !IsValid(Plot) then return end
		surface.PlaySound("ui/buttonclick.wav")
		if IsValid(PlotMenu) then
			PlotMenu:Close()
		end
		local SeedsMenu = vgui.Create("DFrame")
		SeedsMenu:SetTitle("Samen auswählen...")
		SeedsMenu:SetWide(230)
		SeedsMenu:ShowCloseButton(false)
		SeedsMenu:MakePopup()
		SeedsMenu.Paint = function(slf, w, h)
			draw.RoundedBox(4, 0, 0, w, h, Color(45, 45, 45, 255))
		end
		SeedsMenu:ParentToHUD()
		SeedsMenu.Think = function()
			if !IsValid(Plot) or Plot:GetNoDraw() or !ply:Alive() or ply:EyePos():DistToSqr(Plot:GetPos()) > 10000 then
				SeedsMenu:Close()
			end
		end
		local Close = vgui.Create("DButton", SeedsMenu)
		Close:SetSize(50, 20)
		Close:SetPos(SeedsMenu:GetWide() - 52, 2)
		Close:SetText("X")
		Close:SetFont("Farming_Close")
		Close:SetTextColor(color_white)
		Close.Paint = function(self, w, h)
			local col
			if self:IsHovered() then
				col = Color(255, 100, 100)
			else
				col = Color(200, 50, 50)
			end
			draw.RoundedBox(4, 0, 0, w, h, col)
		end
		Close.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			SeedsMenu:Remove()
		end
		local menusize = 40
		for k, v in pairs(seeds) do
			local seed_tbl = FarmingCFG.Crops[k]
			if !seed_tbl then continue end
			local Option = vgui.Create("DButton", SeedsMenu)
			Option:SetPos(10, menusize)
			Option:SetSize(210, 20)
			Option:SetText(seed_tbl.seedname.." (x"..v..")")
			Option.DoClick = function()
				if IsValid(Plot) then
					net.Start("Farming_PlantSeeds")
						net.WriteEntity(Plot)
						net.WriteUInt(k, 16)
					net.SendToServer()
				end
				if IsValid(SeedsMenu) then
					surface.PlaySound("ui/buttonclick.wav")
					SeedsMenu:Remove()
				end
			end
			menusize = menusize + 30
		end
		SeedsMenu:SetTall(menusize)
		SeedsMenu:Center()
	end
	PlotMenu:SetTall(mainsize)
	PlotMenu:SetPos(ScrW() / 2 - PlotMenu:GetWide() / 2, ScrH())
	PlotMenu:MoveTo(ScrW() / 2 - PlotMenu:GetWide() / 2, ScrH() / 2 - PlotMenu:GetTall() / 2, 0.25, 0, 0.5)
end)

local function CropSetup(self, id, crop)
	if !IsValid(crop) then return false end
	local index = CROPTYPES[FarmingCFG.Crops[id].typ].range
	local spot = Vector(math.Rand(index.x[1], index.x[2]), math.Rand(index.y[1], index.y[2]), math.Rand(index.z[1], index.z[2]))
	local ang = self:GetAngles()
	ang:RotateAroundAxis(ang:Up(), 90)
	crop:SetPos(self:GetPos() + ang:Forward() * spot.y + ang:Right() * spot.x + ang:Up() * spot.z)
	crop:SetAngles(Angle(0, math.Rand(0, 360), 0))
	return crop
end

function ENT:AddCrop()
	local id = self:GetID()
	if id == 0 then return end
	local crop = ClientsideModel(FarmingCFG.Crops[id].cropmodel, RENDERGROUP_OPAQUE)
	crop = CropSetup(self, id, crop)
	if crop then
		table.insert(self.Crops, crop)
		crop:SetNoDraw(true)
		crop:SetModelScale(0.1, 0)
		crop:SetModelScale(FarmingCFG.Crops[id].modelscale, 0)
		crop:SetParent(self)
	end
end

function ENT:RemoveCrop(all)
	for i=#self.Crops, 1, -1 do
		SafeRemoveEntity(self.Crops[i])
		table.remove(self.Crops, i)
		if !all then
			break
		end
	end
end

function ENT:Draw()
	self:DrawModel()
	if self:GetNoDraw() then return end
	local plant = self.Plant
	if IsValid(plant) then
		local sys_time = SysTime()
		for i = 0, plant:GetBoneCount() do
			if plant:GetBoneName(i) == "root" then continue end
			plant.bones = plant.bones or {}
			plant.bones["bone"..i] = plant.bones["bone"..i] or {}
			plant.bones["bone"..i][1] = sys_time
			if !plant.bones["bone"..i][2] or !plant.bones["bone"..i][3] then
				plant.bones["bone"..i][2] = plant:GetManipulateBoneAngles(i)
				plant.bones["bone"..i][3] = sys_time
			end
			local movement = plant.bones["bone"..i][2] + Angle(0, math.sin(plant.bones["bone"..i][3] - plant.bones["bone"..i][1] + i) * i * 3, 0)
			plant:ManipulateBoneAngles(i, movement)
		end
		plant:DrawModel()
	end
	for i=1, #self.Crops do
		local crops = self.Crops[i]
		if IsValid(crops) then
			crops:DrawModel()
		end
	end
end

local triangle = {
	{x = -128 * 1.5 + 105, y = -150},
	{x = -128 * 1.5 + 115, y = -135},
	{x = -128 * 1.5 + 105, y = -120}
}

local info_health = Material("gui/gardening/info_health")
local info_water = Material("gui/gardening/info_water")
local info_status = Material("gui/gardening/info_status")
local local_ply

function ENT:DrawTranslucent()
	local_ply = local_ply or LocalPlayer()
	if (local_ply:EyePos():DistToSqr(self:GetPos()) < 22500) then
		local id = self:GetID()
		local water = self:GetWater()
		local ang = self:GetAngles()
		local pos = self:GetPos()
		local pos, ang = Vector(pos.x, pos.y, pos.z + 5), Angle(0, EyeAngles().y - 90, 90)
		cam.Start3D2D(pos, ang, 0.15)
			draw.RoundedBox(0, -133 * 1.5, -170, 105, 65, Color(125, 150, 125, 150))
			surface.SetDrawColor(125, 150, 125, 150)
			draw.NoTexture()
			surface.DrawPoly(triangle)
			if id > 0 then
				surface.SetDrawColor(255, 255, 255, 255)
				surface.SetMaterial(info_health)
				surface.DrawTexturedRect(-124 * 1.5, -175 + 20, 16, 16)
				surface.SetDrawColor(255, 255, 255, 255)
				surface.SetMaterial(info_water)
				surface.DrawTexturedRect(-124 * 1.5 + 32, -175 + 20, 16, 16)
				surface.SetDrawColor(255, 255, 255, 255)
				surface.SetMaterial(info_status)
				surface.DrawTexturedRect(-124 * 1.5 + 64, -175 + 20, 16, 16)
				surface.SetDrawColor(105, 165, 91, 255)
				surface.DrawRect(-124 * 1.5, -175 + 38, 16, 18)
				surface.SetDrawColor(200, 100, 100, 255) 
				surface.DrawRect(-124 * 1.5, -175 + 38, 16, -(18 / 100) * ((self:GetCrops() / CROPTYPES[FarmingCFG.Crops[id].typ].crops) * 100) + 18)
				surface.SetDrawColor(40, 45, 46, 50)
				surface.DrawOutlinedRect(-124 * 1.5, -175 + 38, 16, 18)
				surface.SetDrawColor(105, 165, 91, 255)
				surface.DrawRect(-124 * 1.5 + 32, -175 + 38, 16, 18)
				surface.SetDrawColor(200, 100, 100, 255)
				surface.DrawRect(-124 * 1.5 + 32, -175 + 38, 16, -(18 / 100) * water + 18)
				surface.SetDrawColor(40, 45, 46, 50)
				surface.DrawOutlinedRect(-124 * 1.5 + 32, -175 + 38, 16, 18)
				surface.SetDrawColor(105, 165, 91, 255)
				surface.DrawRect(-124 * 1.5 + 64, -175 + 38, 16, 18)
				surface.SetDrawColor(200, 100, 100, 255)
				surface.DrawRect(-124 * 1.5 + 64, -175 + 38, 16, -(18 / 100) * self:GetSize() + 18)
				surface.SetDrawColor(40, 45, 46, 50)
				surface.DrawOutlinedRect(-124 * 1.5 + 64, -175 + 38, 16, 18)
			end
		cam.End3D2D()
		cam.Start3D2D(pos, ang, 0.05)
			draw.SimpleText(id > 0 and (FarmingAddon.GetPlantName(id)..(water > 0 and "" or " (Verstorben)")) or "Samen einfügen...", "Farming_PlantPot", -335 * 1.5 + 64, -540 + 38, water > 0 and color_black or Color(100, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
			draw.SimpleText(IsValid(self:Getowning_ent()) and self:Getowning_ent():Name() or "Niemand", "Farming_PlantPot", -335 * 1.5 + 64, -390 + 38, color_black, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
			--draw.SimpleText(IsValid(self:Getowning_ent()) and self:Getowning_ent():Name() or "Niemand", "Farming_PlantPot", -335 * 1.5 + 64, -390 + 38, color_black, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
		cam.End3D2D()
	end
end

function ENT:ClearModels()
	if IsValid(self.Plant) then
		self.Plant:Remove()
	end
	self:RemoveCrop(true)
end

local dead_plant = Color(50, 50, 50, 255)
function ENT:Think()
	if self == NULL then return end
	local id = self:GetID()
	if id == 0 then return end
	local plant = self.Plant
	local model = CROPTYPES[FarmingCFG.Crops[id].typ].model
	if !IsValid(plant) or plant:GetModel() != model then
		if IsValid(self.Plant) then
			self.Plant:Remove()
		end
		self.Plant = ClientsideModel(model, RENDERGROUP_OPAQUE)
		plant = self.Plant
		if !IsValid(plant) then return end
		plant:SetNoDraw(true)
		plant:SetPos(self:GetPos())
		plant:SetAngles(self:GetAngles())
		plant:SetParent(self)
	end
	if IsValid(plant) then
		local pos = self:GetPos()
		local crops_draw = #self.Crops
		if !IsValid(plant:GetParent()) then
			plant:SetAngles(self:GetAngles())
			plant:SetParent(self)
			for i=1, crops_draw do
				local crops = self.Crops[i]
				if IsValid(crops) then
					crops:SetParent(self)
				end
			end
		end
		if self:GetWater() <= 0 then
			plant:SetRenderMode(RENDERMODE_TRANSCOLOR)
			plant:SetColor(dead_plant)
		else
			plant:SetColor(color_white)
		end
		plant:SetPos(self:GetPos())
		plant:SetModelScale(self:GetVisualSize(), 0)
		local crops_amt = self:GetCrops()
		if crops_draw != crops_amt then
			if crops_draw > crops_amt then
				local remove = crops_draw - crops_amt
				for i=1, remove do
					self:RemoveCrop()
				end
			else
				local add = crops_amt - crops_draw
				for i=1, add do
					self:AddCrop()
				end
			end
		end
	end
end