TOOL.Category = "Construction"
TOOL.Name = "Money Pot"
TOOL.ClientConVar["weld"] = 1

if SERVER then
	CreateConVar("sbox_maxmoney_pots", 10, FCVAR_NOTIFY)
end

cleanup.Register("money_pots")

TOOL.Information = {
	{name = "left"}
}

if CLIENT then
	language.Add("tool.money_pot.name", "Money Pot")
	language.Add("tool.money_pot.desc", "Bewahrt Geld in einem Gefäß auf.")
	language.Add("tool.money_pot.left", "Money Pot erstellen")
	language.Add("max_money_pots", "Maximale Money Pots")
	language.Add("Undone_Money Pot", "Undone Money Pot")
	language.Add("SBoxLimit_money_pots", "You've hit the Money Pot Limit!")
	language.Add("Cleanup_money_pots", "Money Pots")
	language.Add("Cleaned_money_pots", "Cleaned up all Money Pots")

	function TOOL.BuildCPanel(cp)
		cp:AddControl("Header", {Text = "#tool.money_pot.name", Description = "Hiermit kann Geld in einem Gefäß aufbewahrt werden."})
		cp:AddControl("Checkbox", {Label = "Prop mit Money Pot verbinden", Command = "money_pot_weld"})
	end
end

function TOOL:UpdateGhostMoneyPot(ent, ply)
	if !IsValid(ent) then return end
	local tr = ply:GetEyeTrace()
	if !tr.Hit then return end
	local tr_ent = tr.Entity
	if IsValid(tr_ent) and (tr_ent:IsPlayer() or tr_ent:GetClass() == "money_pot") then
		ent:SetNoDraw(true)
		return
	end
	local ang = tr.HitNormal:Angle()
	ang.pitch = ang.pitch + 90
	ent:SetPos(tr.HitPos - tr.HitNormal * ent:OBBMins().z)
	ent:SetAngles(ang)
	ent:SetNoDraw(false)
end

function TOOL:Think()
	if (!IsValid(self.GhostEntity) or self.GhostEntity:GetModel() != "models/props_lab/powerbox02b.mdl") then
		self:MakeGhostEntity("models/props_lab/powerbox02b.mdl", Vector(0, 0, 0), Angle(0, 0, 0))
	end
	self:UpdateGhostMoneyPot(self.GhostEntity, self:GetOwner())
end

function TOOL:LeftClick(tr)
	local ent = tr.Entity
	if IsValid(ent) and ent:IsPlayer() then return false end
	if IsValid(ent) and ent:GetClass() == "money_pot" then return false end
	if SERVER and !util.IsValidPhysicsObject(ent, tr.PhysicsBone) then return false end
	if CLIENT then return true end
	local ply = self:GetOwner()
	local ang = tr.HitNormal:Angle()
	ang.pitch = ang.pitch + 90
	local box = MakeMoneyPot(ply, tr.HitPos, ang)
	if !IsValid(box) then return false end
	box:SetPos(tr.HitPos - tr.HitNormal * box:OBBMins().z)
	local weld
	local phys = box:GetPhysicsObject()
	if (IsValid(ent) and !ent:IsWorld() and self:GetClientNumber("weld") ~= 0) then
		weld = constraint.Weld(box, ent, 0, tr.PhysicsBone, 0)
		ent:DeleteOnRemove(box)
	elseif IsValid(phys) then
		phys:EnableMotion(false)
	end
	DoPropSpawnedEffect(box)
	undo.Create("Money Pot")
		undo.AddEntity(box)
		undo.AddEntity(weld)
		undo.SetPlayer(ply)
	undo.Finish()
	ply:AddCleanup("money_pots", box)
	ply:AddCleanup("money_pots", weld)
	return true
end