include("shared.lua")

SWEP.DrawCrosshair = false

function SWEP:GetViewModelPosition(pos , ang)
	pos, ang = LocalToWorld(Vector(20, -10, -15), Angle(0, 0, 0), pos, ang)
	return pos, ang
end

local function kernel_init(particle, vel)
	particle:SetVelocity(vel or VectorRand():GetNormalized() * 15)
	particle:SetGravity(Vector(0, 0, -200))
	particle:SetLifeTime(0)
	particle:SetDieTime(math.Rand(4, 10))

	local size = math.Rand(0.75, 1.25)

	particle:SetStartSize(size)
	particle:SetEndSize(size)
	particle:SetStartAlpha(255)
	particle:SetEndAlpha(0)
	particle:SetCollide(true)
	particle:SetBounce(math.Rand(0.1, 0.3))
	particle:SetRoll(math.pi * math.Rand(0, 1))
	particle:SetRollDelta(math.pi * math.Rand(-4, 4))
end

local emitter = ParticleEmitter(Vector(0, 0, 0))
local function kernel_effect(ply, chance)
	local attachid = ply:LookupAttachment("eyes")

	emitter:SetPos(ply:GetPos())

	local angpos = ply:GetAttachment(attachid)
	if !angpos then return end


	local fwd, pos
	if LocalPlayer() == ply then
		fwd = ply:GetAimVector():GetNormalized()
		pos = ply:GetShootPos() + gui.ScreenToVector(ScrW() / 2, ScrH() / 4 * 3) * 10
	else
		fwd = (angpos.Ang:Forward() - angpos.Ang:Up()):GetNormalized()
		pos = angpos.Pos + fwd * 3
	end

	for i=1, chance do
		local particle = emitter:Add("particle/popcorn-kernel", pos)

		if particle then
			local dir = VectorRand():GetNormalized()

			kernel_init(particle, ((fwd) + dir):GetNormalized() * math.Rand(0, 35) + (ply:GetVelocity() / 2))
		end
	end
end

net.Receive("Popcorn_Eat",function () 
	local ply = net.ReadEntity()
	if !IsValid(ply) or !IsValid(ply:GetActiveWeapon()) or ply:GetActiveWeapon():GetClass() != "weapon_popcorn" then return end
	kernel_effect(ply, math.random(6, 12))

	local entindex = ply:EntIndex()
	timer.Create("Popcorn_Eat"..entindex, 0.7, 5, function()
		if !IsValid(ply) or !ply:Alive() then timer.Remove("Popcorn_Eat"..entindex) return end

		kernel_effect(ply, math.random(1, 3))
	end)
end)