local function ignore( self )
	self.ignore = not self.ignore
end

local KeyHandler = Class(function(self, inst)
	self.inst = inst
	self.ignore = false
	self.ignore_event = net_event(self.inst.GUID, "ignore")
	self.handler = TheInput:AddKeyHandler(function(key, down) self:OnRawKey(key, down) end )
	self.inst:ListenForEvent( "ignore", function(inst) ignore( inst.components.keyhandler ) end)
end)

function KeyHandler:StartIgnoring()
	self.ignore_event:push()
end

function KeyHandler:StopIgnoring()
	self.ignore_event:push()
end

function KeyHandler:OnRawKey(key, down)
	local player = ThePlayer
  	if (key and not down) and not IsPaused() and not self.ignore then
      	player:PushEvent("keypressed", {inst = self.inst, player = player, key = key})
    elseif key and down and not IsPaused() and not self.ignore then
      	player:PushEvent("keydown", {inst = self.inst, player = player, key = key})
  	end
end

function KeyHandler:AddActionListener(Namespace, Key, Action)
	self.inst:ListenForEvent("keypressed", function(inst, data)
		if data.inst == ThePlayer then
			if data.key == Key then
				local x,y,z = ( TheInput:GetWorldPosition() or Vector3(0,0,0) ):Get()
				if TheWorld.ismastersim then
					ThePlayer:PushEvent("keyaction"..Namespace..Action, { Namespace = Namespace, Action = Action, Fn = MOD_RPC_HANDLERS[Namespace][MOD_RPC[Namespace][Action].id], x = x, y = y, z = z })
				else
					SendModRPCToServer( MOD_RPC[Namespace][Action], x, y, z )
				end
			end
		end
	end)

	if TheWorld.ismastersim then
		self.inst:ListenForEvent("keyaction"..Namespace..Action, function(inst, data)
			if not data.Action == Action and not data.Namespace == Namespace then
				return
			end
			
			data.Fn(inst, data.x, data.y, data.z)
		end) 
    end
end

return KeyHandler