SWEP.Base = "weapon_basekit"

SWEP.ViewModel = Model("models/teh_maestro/popcorn.mdl")
SWEP.WorldModel = Model("models/teh_maestro/popcorn.mdl")
SWEP.ShowWorldModel = false

SWEP.Spawnable = true

SWEP.PrintName = "Popcorn"
SWEP.Instructions = "Linksklick, um Popcorn zu essen.\nRechtsklick, um den Eimer weg zu werfen."

SWEP.Primary.Delay = 5
SWEP.Primary.Ammo = "none"
SWEP.Secondary.Ammo = "none"

SWEP.Slot = 0
SWEP.SlotPos = 1

SWEP.Primary.Ammo = "none"
SWEP.Primary.ClipSize = 30
SWEP.Primary.DefaultClip = 30
SWEP.Primary.Automatic = false

SWEP.FoodSource = 3

SWEP.WElements = {
	["w_popcorn"] = {type = "Model", model = "models/teh_maestro/popcorn.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4, 6, 0), angle = Angle(0, 0, 180), size = Vector(0.7, 0.7, 0.7), color = Color(255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {}}
}

if CLIENT then
	function SWEP:CustomAmmoDisplay()
		self.AmmoDisplay = self.AmmoDisplay or {}
		self.AmmoDisplay.Draw = true
		self.AmmoDisplay.PrimaryClip = self:Clip1()
		return self.AmmoDisplay
	end
end

DEFINE_BASECLASS("weapon_basekit")

function SWEP:Initialize()
	self:SetHoldType("slam")

	return BaseClass.Initialize(self)
end

local crisps_eat = Sound("crisps/eat.wav")
function SWEP:PrimaryAttack()
	if self:Clip1() <= 0 then return end

	local owner = self:GetOwner()

	if !IsValid(owner) then return end

	self:TakePrimaryAmmo(1)
	self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
	owner:SetAnimation(PLAYER_ATTACK1)

	if SERVER then
		if owner.getDarkRPVar and owner:getDarkRPVar("Energy") then
			owner:setSelfDarkRPVar("Energy", math.min(owner:getDarkRPVar("Energy") + self.FoodSource, 100))
		end

		owner:EmitSound(crisps_eat, 70)

		net.Start("Popcorn_Eat")
			net.WriteEntity(owner)
		net.Broadcast()
	end
end

local throwsound = Sound("weapons/slam/throw.wav")
function SWEP:SecondaryAttack()
	self:SetNextSecondaryFire(CurTime() + 1)

	local owner = self:GetOwner()
	if !IsValid(owner) then return end

	self:EmitSound(throwsound)
	owner:SetAnimation(PLAYER_ATTACK1)
	owner:ViewPunch(Angle(-10, 0, 0))

	if !SERVER then return end

	local bucket = ents.Create("popcorn")
	if !IsValid(bucket) then return end

	bucket:SetPos(owner:GetShootPos())
	bucket:SetOwner(owner)
	bucket:SetPhysicsAttacker(owner)
	bucket.Owner = owner
	bucket:Spawn() 
	bucket:Activate()

	local phys = bucket:GetPhysicsObject()
	if IsValid(phys) then
		phys:SetVelocity(owner:GetPhysicsObject():GetVelocity())
		phys:AddVelocity(owner:EyeAngles():Forward() * 128 * phys:GetMass())
		phys:AddAngleVelocity(VectorRand() * 128 * phys:GetMass())
	end

	owner:StripWeapon(self.ClassName)
end

function SWEP:Think()
	local owner = self:GetOwner()
	if !IsValid(owner) then return end

	if owner:Crouching() and self:GetHoldType() == "slam" then
		self:SetHoldType("knife")
	elseif self:GetHoldType() == "knife" then
		self:SetHoldType("slam")
	end
end