if SERVER then
	AddCSLuaFile()
end

SWEP.PrintName = "Taschendiebstahl"
SWEP.Purpose = "Hiermit kann man die Waffen und das Geld deiner Mitbürger stehlen.\n\nErzeugt Geräusche dabei und ist sichtbar."
SWEP.Instructions = "Linksklick um gehaltene Waffe zu stehlen.\nRechtsklick um Geld zu stehlen.\n\nMehrfach eine der beiden Maustasten drücken, um den Vorgang zu beschleunigen."

SWEP.HoldType = "normal"
SWEP.Spawnable = true
SWEP.UseHands = true
SWEP.ViewModel = Model("models/weapons/c_arms.mdl")
SWEP.WorldModel = ""

SWEP.Primary.Clipsize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"

SWEP.Secondary.Clipsize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"

SWEP.Slot = 1
SWEP.SlotPos = 10
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = true

SWEP.PickpocketMinMoney = 250
SWEP.PickpocketMaxMoney = 1000
SWEP.PickpocketDuration_Money = 6
SWEP.PickpocketDuration_Weapon = 10
SWEP.PickpocketDistance = 60
SWEP.PickpocketFailureChance = 0.25
SWEP.AllowPickpocketSpeedup = true
SWEP.SpeedUpIncrement = 0.2
SWEP.AllowWeaponPickpocket = true
SWEP.AllowMoneyPickpocket = true
SWEP.SoundFrequency = 1

function SWEP:SetupDataTables()
	self:NetworkVar("Bool", 0, "Pickpocketing")
	self:NetworkVar("Bool", 1, "PickpocketMoney")
	self:NetworkVar("Float", 0, "PickpocketTime")
	self:NetworkVar("Entity", 0, "PickpocketTarget")
end

function SWEP:DoDrawCrosshair()
	if self:GetPickpocketing() then
		return true
	end
end

function SWEP:Initialize()
	self:SetHoldType(self.HoldType)
end

function SWEP:PreDrawViewModel(vm)
	return true
end

function SWEP:Deploy()
	self:SetPickpocketing(false)
	self:SetPickpocketMoney(false)
	self:SetPickpocketTime(0)
	self:SetPickpocketTarget(NULL)
	return true
end

function SWEP:Holster()
	self:SetPickpocketing(false)
	self:SetPickpocketMoney(false)
	self:SetPickpocketTime(0)
	self:SetPickpocketTarget(NULL)
	return true
end

local distance = SWEP.PickpocketDistance * SWEP.PickpocketDistance
function SWEP:CanPickpocket(target)
	if IsValid(target) and (target:IsPlayer() or IsValid(target.PlayerEntity)) and target:GetPos():DistToSqr(self.Owner:GetPos()) < distance then
		local canPickpocket = hook.Run("canPickpocket", self.Owner, target)
		if canPickpocket == false then return false end
		return true
	else
		return false
	end
end

function SWEP:Pickpocket(target, money)
	self:SetPickpocketing(true)
	local time = money and self.PickpocketDuration_Money or self.PickpocketDuration_Weapon
	time = hook.Run("pickPocketTime", self, time, target) or time
	self:SetPickpocketTime(CurTime() + time)
	self:SetPickpocketTarget(target)
	self:SetPickpocketMoney(money)
end

function SWEP:PrimaryAttack()
	if !SERVER then return true end
	local target = self.Owner:GetEyeTrace().Entity
	if self:GetPickpocketing() then
		if self.AllowPickpocketSpeedup then
			self:SetNextPrimaryFire(CurTime() + 0.08)
			self:SetNextSecondaryFire(CurTime() + 0.08)
			self:SetPickpocketTime(self:GetPickpocketTime() - self.SpeedUpIncrement)
		end
	else
		if self.AllowWeaponPickpocket and self:CanPickpocket(target) then
			if IsValid(target.PlayerEntity) or target:isArrested() then DarkRP.notify(self.Owner, 1, 5, "Diese Person liegt gerade auf dem Boden und hält daher keine Waffe!") return end
			if target:isArrested() then DarkRP.notify(self.Owner, 1, 5, "Diese Person ist inhaftiert und trägt daher keine Waffe!") return end
			self:Pickpocket(target, false)
			hook.Run("onPlayerStartedStealing", self.Owner, target)
		end
	end
end

function SWEP:SecondaryAttack()
	if !SERVER then return true end
	local target = self.Owner:GetEyeTrace().Entity
	if self:GetPickpocketing() then
		if self.AllowPickpocketSpeedup then
			self:SetNextPrimaryFire(CurTime() + 0.08)
			self:SetNextSecondaryFire(CurTime() + 0.08)
			self:SetPickpocketTime(self:GetPickpocketTime() - self.SpeedUpIncrement)
		end
	elseif self.AllowMoneyPickpocket and self:CanPickpocket(target) then
		self:Pickpocket(target, true)
		hook.Run("onPlayerStartedStealing", self.Owner, IsValid(target.PlayerEntity) and target.PlayerEntity or target)
	end
end

if SERVER then
	function SWEP:Think()
		local owner = self:GetOwner()
		if !IsValid(owner) then return end
		if self:GetPickpocketing() then
			self:SetHoldType("revolver")
			local target = self:GetPickpocketTarget()
			if !self:CanPickpocket(target) or owner:GetEyeTrace().Entity != target then
				self:SetPickpocketing(false)
			else
				if !self.NextSound or self.NextSound < CurTime() then
					owner:EmitSound("physics/body/body_medium_impact_soft"..math.random(1, 7)..".wav", 60, 100, 0.25)
					self.NextSound = CurTime() + self.SoundFrequency
				end
				if self:GetPickpocketTime() < CurTime() then
					self:SetPickpocketing(false)
					if math.Rand(0, 1) > self.PickpocketFailureChance then
						target = IsValid(target.PlayerEntity) and target.PlayerEntity or target
						if self:GetPickpocketMoney() then
							local money = math.Clamp(target:getDarkRPVar("money"), 0, math.floor(math.random(self.PickpocketMinMoney, self.PickpocketMaxMoney) * (owner:Team() == TEAM_MASTERTHIEF and 1.25 or 1)))
							target:addMoney(-money)
							owner:addMoney(money)
							DarkRP.notify(owner, 0, 4, "Du hast $"..string.Comma(money).." gestohlen.")
							hook.Run("onPlayerStoleMoney", owner, target, money)
						else
							local active_wep = target:GetActiveWeapon()
							if active_wep:IsValid() then
								local class = active_wep:GetClass()
								local canDrop = hook.Call("canDropWeapon", GAMEMODE, target, active_wep)
								local tm = target:Team()
								if RPExtraTeams[tm] and RPExtraTeams[tm].weapons and table.HasValue(RPExtraTeams[tm].weapons, class) or GAMEMODE.Config.DisallowDrop[class] or !canDrop then
									DarkRP.notify(owner, 1, 4, "Du kannst dies nicht stehlen!")
									return
								end
								hook.Run("onPlayerStoleWeapon", owner, target, active_wep)
								local new_wep = owner:Give(class, true)
								local weapon_exists = false
								if !IsValid(new_wep) then
									new_wep = owner:GetWeapon(class)
									weapon_exists = true
								end
								if !IsValid(new_wep) then return end
								local ammo_typ = new_wep:GetPrimaryAmmoType()
								local prim_ammo = target:GetAmmoCount(new_wep:GetPrimaryAmmoType()) or 0
								local active_clip = active_wep:Clip1() or -1
								if !weapon_exists then
									new_wep:SetClip1(active_clip)
								else
									prim_ammo = prim_ammo + (active_clip != -1 and active_clip or 0)
								end
								owner:GiveAmmo(prim_ammo, ammo_typ, true)
								target:StripWeapon(class)
								target:SetAmmo(0, ammo_typ)
								DarkRP.notify(owner, 0, 4, "Du hast "..(new_wep:GetPrintName() or class).." gestohlen.")
							else
								DarkRP.notify(owner, 1, 4, "Diese Person trägt keine Waffe!")
							end
						end
					else
						DarkRP.notify(owner, 1, 4, "Diebstahl fehlgeschlagen!")
					end
				end
			end
		elseif self:GetHoldType() != self.HoldType then
			self:SetHoldType(self.HoldType)
		end
	end
else
	local gradientup = Material("gui/gradient_up")
	local gradientdown = Material("gui/gradient_down")

	function SWEP:DrawProgressBar(label, color, filled)
		filled = math.Clamp(filled, 0, 1)
		local w, h = 300, 20
		local centerx, centery = ScrW() / 2, ScrH() / 2
		local x, y = centerx - w / 2, centery - h / 2
		surface.SetDrawColor(color_white)
		surface.DrawOutlinedRect(x, y, w, h)
		surface.SetDrawColor(color)
		surface.SetMaterial(gradientdown)
		surface.DrawTexturedRect(x + 2, y + 2, (w - 4) * filled, h - 4)
		surface.SetDrawColor(Color(color.r / 2, color.g / 2, color.b/ 2))
		surface.SetMaterial(gradientup)
		surface.DrawTexturedRect(x + 2, y + 2, (w - 4) * filled, h - 4)
		draw.SimpleTextOutlined(label, "DermaDefaultBold", centerx, centery - 1, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 0, 0))
	end

	function SWEP:DrawHUD()
		local trace = self.Owner:GetEyeTrace()
		if self:CanPickpocket(trace.Entity) then
			local scrw, scrh = ScrW() / 2, ScrH() - 110
			draw.SimpleTextOutlined("[Linksklick] Waffe stehlen", "mg_instructions", scrw, scrh, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 1, color_black)
			draw.SimpleTextOutlined("[Rechtsklick] Geld stehlen", "mg_instructions2", scrw, scrh + 25, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 1, color_black)
		end
		if self:GetPickpocketing() then
			local text = "Waffe stehlen..."
			local color = Color(255, 0, 0)
			if self:GetPickpocketMoney() then
				text = "Geld stehlen..."
				color = Color(0, 255, 0)
			end
			local dur = self:GetPickpocketMoney() and self.PickpocketDuration_Money or self.PickpocketDuration_Weapon
			self:DrawProgressBar(text, color, (CurTime() - (self:GetPickpocketTime() - dur)) / dur)
		end
	end
end