if SERVER then
	CreateConVar("sbox_maxkeypads", 10)
end

TOOL.Category = "Construction"
TOOL.Name = "Keypad"
TOOL.ClientConVar["weld"] = "1"
TOOL.ClientConVar["freeze"] = "1"
TOOL.ClientConVar["password"] = "1234"
TOOL.ClientConVar["secure"] = "1"
TOOL.ClientConVar["repeats_granted"] = "0"
TOOL.ClientConVar["repeats_denied"] = "0"
TOOL.ClientConVar["length_granted"] = "5"
TOOL.ClientConVar["length_denied"] = "0"
TOOL.ClientConVar["delay_granted"] = "0"
TOOL.ClientConVar["delay_denied"] = "0"
TOOL.ClientConVar["init_delay_granted"] = "0"
TOOL.ClientConVar["init_delay_denied"] = "0"
TOOL.ClientConVar["key_granted"] = "0"
TOOL.ClientConVar["key_denied"] = "0"

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

cleanup.Register("keypads")

if CLIENT then
	language.Add("tool.keypad.name", "Keypad")
	language.Add("tool.keypad.left", "Keypad erstellen/aktualisieren")
	language.Add("tool.keypad.right", "Keypad-Einstellungen kopieren")
	language.Add("tool.keypad.desc", "Hiermit können Keypads erstellt werden, welche vielseitig verwendet werden können.")
	language.Add("max_keypads", "Maximale Keypads")
	language.Add("Undone_Keypad", "Undone Keypad")
	language.Add("Cleanup_keypads", "Keypads")
	language.Add("Cleaned_keypads", "Cleaned up all Keypads")
	language.Add("SBoxLimit_keypads", "You've hit the Keypadlimit!")
end

function TOOL:SetupKeypad(ent, pass)
	local data = {
		Password = pass,
		RepeatsGranted = self:GetClientNumber("repeats_granted"),
		RepeatsDenied = self:GetClientNumber("repeats_denied"),
		LengthGranted = self:GetClientNumber("length_granted"),
		LengthDenied = self:GetClientNumber("length_denied"),
		DelayGranted = self:GetClientNumber("delay_granted"),
		DelayDenied = self:GetClientNumber("delay_denied"),
		InitDelayGranted = self:GetClientNumber("init_delay_granted"),
		InitDelayDenied = self:GetClientNumber("init_delay_denied"),
		KeyGranted = self:GetClientNumber("key_granted"),
		KeyDenied = self:GetClientNumber("key_denied"),
		Secure = util.tobool(self:GetClientNumber("secure")),
		Owner = self:GetOwner()
	}
	ent:SetData(data)
end

function TOOL:LeftClick(tr)
	local ent = tr.Entity
	if IsValid(ent) and ent:IsPlayer() then return false end
	local ply = self:GetOwner()
	local password = self:GetClientNumber("password")
	if password == nil or #tostring(password) > 4 or (string.find(tostring(password), "0")) then
		if CLIENT and IsFirstTimePredicted() then
			ply:PrintMessage(3, "Ungültiges Passwort!")
		end
		return false
	end
	if CLIENT then return true end
	if (ent:GetClass():lower() == "keypad") and (ent:GetData().Owner == ply or ply:IsAdmin()) then
		self:SetupKeypad(ent, password)
		return true
	end
	local spawn_pos = tr.HitPos + tr.HitNormal
	if !self:GetWeapon():CheckLimit("keypads") then return false end
	local ent = ents.Create("keypad")
	if !IsValid(ent) then return false end
	ent:SetPos(spawn_pos)
	ent:SetAngles(tr.HitNormal:Angle())
	ent:Spawn()
	ent:SetPlayer(ply)
	ent:SetCollisionGroup(COLLISION_GROUP_WORLD)
	DoPropSpawnedEffect(ent)
	local freeze = util.tobool(self:GetClientNumber("freeze"))
	local weld = util.tobool(self:GetClientNumber("weld"))
	local phys = ent:GetPhysicsObject()
	if (freeze or weld) and IsValid(phys) then
		phys:EnableMotion(false)
	end
	if weld then
		weld = constraint.Weld(ent, ent, 0, 0, 0, true, false)
	end
	self:SetupKeypad(ent, password)
	undo.Create("Keypad")
		undo.AddEntity(ent)
		undo.SetPlayer(ply)
	undo.Finish()
	ply:AddCount("keypads", ent)
	ply:AddCleanup("keypads", ent)
	return true
end

function TOOL:RightClick(tr)
	local ent = tr.Entity
	if !IsValid(ent) or ent:GetClass():lower() != "keypad" then return false end
	if CLIENT then return true end
	local ply = self:GetOwner()
	local data = ent:GetData()
	if data.Owner != ply and !ply:IsAdmin() then return false end
	ply:ConCommand("keypad_password "..data.Password)
	ply:ConCommand("keypad_secure "..(data.Secure == true and 1 or 0))
	ply:ConCommand("keypad_key_granted "..data.KeyGranted)
	ply:ConCommand("keypad_key_denied "..data.KeyDenied)
	ply:ConCommand("keypad_repeats_granted "..data.RepeatsGranted)
	ply:ConCommand("keypad_repeats_denied "..data.RepeatsDenied)
	ply:ConCommand("keypad_length_granted "..data.LengthGranted)
	ply:ConCommand("keypad_length_denied "..data.LengthDenied)
	ply:ConCommand("keypad_delay_granted "..data.DelayGranted)
	ply:ConCommand("keypad_delay_denied "..data.DelayDenied)
	ply:ConCommand("keypad_init_delay_granted "..data.InitDelayGranted)
	ply:ConCommand("keypad_init_delay_denied "..data.InitDelayDenied)
	return true
end

function TOOL:UpdateGhostKeypad(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():lower() == "keypad") then
		ent:SetNoDraw(true)
		return
	end
	local ang = tr.HitNormal:Angle()
	ent:SetPos(tr.HitPos + tr.HitNormal)
	ent:SetAngles(ang)
	ent:SetNoDraw(false)
end

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

if CLIENT then
	local function ResetSettings(ply)
		RunConsoleCommand("keypad_repeats_granted", "0")
		RunConsoleCommand("keypad_repeats_denied", "0")
		RunConsoleCommand("keypad_length_granted", "5")
		RunConsoleCommand("keypad_length_denied", "0")
		RunConsoleCommand("keypad_delay_granted", "0")
		RunConsoleCommand("keypad_delay_denied", "0")
		RunConsoleCommand("keypad_init_delay_granted", "0")
		RunConsoleCommand("keypad_init_delay_denied", "0")
	end
	concommand.Add("keypad_reset", ResetSettings)

	local ConVarsDefault = TOOL:BuildConVarList()
	function TOOL.BuildCPanel(CPanel)
		CPanel:AddControl("Header", {Description = "#tool.keypad.desc"})
		CPanel:AddControl("ComboBox", {MenuButton = 1, Folder = "keypad", Options = {["#preset.default"] = ConVarsDefault}, CVars = table.GetKeys(ConVarsDefault)})
		local r = CPanel:TextEntry("Zugriffspasswort", "keypad_password")
		r:SetTall(22)
		CPanel:ControlHelp("Maximale Länge: 4 Ziffern\nEs werden nur Zahlen von 1-9 erlaubt.")
		CPanel:CheckBox("Sicherheitsmodus", "keypad_secure")
		CPanel:CheckBox("An Welt schweißen", "keypad_weld")
		CPanel:CheckBox("Einfrieren", "keypad_freeze")
		local ctrl = vgui.Create("CtrlNumPad", CPanel)
		ctrl:SetConVar1("keypad_key_granted")
		ctrl:SetConVar2("keypad_key_denied")
		ctrl:SetLabel1("Zugriff gewährt - Taste")
		ctrl:SetLabel2("Zugriff verweigert - Taste")
		CPanel:AddPanel(ctrl)
		local granted = vgui.Create("DForm")
		granted:SetName("Zugriff gewährt - Einstellungen")
		granted:NumSlider("Haltelänge:", "keypad_length_granted", 0, 10, 2)
		granted:NumSlider("Initiale Verzögerung:", "keypad_init_delay_granted", 0, 10, 2)
		granted:NumSlider("Wdh. Verzögerung:", "keypad_delay_granted", 0, 10, 2)
		granted:NumSlider("Wiederholungen:", "keypad_repeats_granted", 0, 5, 0)
		CPanel:AddItem(granted)
		local denied = vgui.Create("DForm")
		denied:SetName("Zugriff verweigert - Einstellungen")
		denied:NumSlider("Haltelänge:", "keypad_length_denied", 0, 10, 2)
		denied:NumSlider("Initiale Verzögerung:", "keypad_init_delay_denied", 0, 10, 2)
		denied:NumSlider("Wdh. Verzögerung:", "keypad_delay_denied", 0, 10, 2)
		denied:NumSlider("Wiederholungen:", "keypad_repeats_denied", 0, 5, 0)
		CPanel:AddItem(denied)
		CPanel:Button("Standardeinstellungen", "keypad_reset")
		CPanel:Help("")
		local faq = CPanel:Help("Information")
		faq:SetFont("GModWorldtip")
		CPanel:Help("Du kannst dein Passwort über den Nummernblock deiner Tastatur eingeben.\n\nSollte dies nicht funktionieren, muss dieser zuerst mit der NUM-Taste aktiviert werden.")
	end
end