function fishing.SetPlayerItemCount(ply, class, count)
	local stats = fishing.GetStats(ply)

	local inv = table.Copy(stats.inventory or {})

	if count == 0 then
		inv[class] = nil
	else
		inv[class] = count
	end

	stats.inventory = inv
end

function fishing.AddPlayerItem(ply, class)
	fishing.SetPlayerItemCount(ply, class, (fishing.GetPlayerInventory(ply)[class] or 0) + 1)
end

function fishing.RemovePlayerItem(ply, class)
	local count = fishing.GetPlayerInventory(ply)[class] or 0
	if count > 0 then
		fishing.SetPlayerItemCount(ply, class, count - 1)
		return true
	end
end

function fishing.DropPlayerItem(ply, class)
	local wep = ply:GetActiveWeapon()
	
	if wep.ClassName == "weapon_fishing" and wep.dt.hook.attached.Bait:IsValid() then return false end	

	if fishing.RemovePlayerItem(ply, class) then
		local ent = fishing.CreateEntity(class)

		if ent then
			local pos 
			
			if wep.ClassName == "weapon_fishing" and wep.dt.length < 10 then
				ent:SetPos(wep.dt.hook:GetPos())
				ent:Spawn()
				
				if ent.IsFishingBait or ent.IsFishingFish then
					wep:AttachToHook(ent)
				end
				
				ply:EmitSound("ambient/levels/citadel/pod_close1.wav", 60, math.random(200, 220))
			else
				ent:SetPos(util.QuickTrace(ply:EyePos(), ply:GetAimVector() * 150, ply).HitPos)
				ent:Spawn()
				ent:DropToFloor()
			end
			
			net.Start("fishing_refresh_inventory")
			net.Send(ply)
			
			return ent
		end
	end
end

util.AddNetworkString("fishing_refresh_inventory")

function fishing.PickupPlayerItem(ply)
	local wep = ply:GetActiveWeapon() 
	
	if wep.ClassName == "weapon_fishing" and wep.dt.hook:IsValid() then
		local ent = wep.dt.hook.attached.Bait		
				
		if wep.dt.hook.attached.Fish:IsValid() then
			ent = wep.dt.hook.attached.Fish
		end
				
		if ent:IsValid() and wep.dt.length == 1 then
			fishing.AddPlayerItem(wep.Owner, ent.FishingClassName)
			ply:EmitSound("ambient/levels/citadel/pod_open1.wav", 60, math.random(200, 220))
			ent:Remove()
			
			return true
		end
	end
end

function fishing.ReleasePlayerItem(ply)
	local wep = ply:GetActiveWeapon() 
	if wep.ClassName == "weapon_fishing" and wep.dt.hook:IsValid() then
		wep:DetatchFromHook()
	end
end


concommand.Add("fishing_drop_item", function(ply, _, args)
	fishing.DropPlayerItem(ply, args[1])		
end)

concommand.Add("fishing_pickup_item", function(ply, _, args)
	if not fishing.PickupPlayerItem(ply) then
		fishing.DropPlayerItem(ply, args[1])		
	end
end)			

concommand.Add("fishing_release_item", function(ply, _, args)
	fishing.ReleasePlayerItem(ply)
end)