 		client.send = (data)->
 			@write(JSON.stringify(data))
 
-		client.on 'error', (e)->
+		client.on 'error', (e)=>
 			console.log('error', e)
 			console.log();
+			@emit 'error', e
 
 		client.on 'data', @dataHandler
+		client.on 'data', (data)=>
+			@emit 'tcpMessage', data
 
 		# events to forward
 		client.on 'connection', ()=>
 			if (room)
 				@joinRoom(room)
 			@emit('connected')
+			@emit('tcpConnect', client)
 
 	dataHandler: (data)=>
 		if (typeof data == 'string')

			@messageHandler msg for msg in data.messages
			return
		if (data.type == 'rpc')
			@rpcHandlers[data.id]?(data.result)
			delete @rpcHandlers[data.id]

	messageHandler: (msg)->
		switch msg.type
			when 'ping' then @sendRPC 'pong'
			else
				console.log('Got this message', msg)

	sendRPC: (name, args, callback)->
		if (args == undefined)

		if (args not instanceof Array)
			args = [args]
		rpcId = ++apiId

		@rpcHandlers[rpcId] = 
			callback: callback
			type: name

		client.send
			type: 'rpc'
			id: rpcId
			name: name
			args: args
			
	send: (data)->
		client.send data

	# sane functions. This is the actual API
	# any function who differs in name from the ttfm ones have a copy that calls said ttfm function
	# this is for API compatibility between ttapi and plugapi
	joinRoom: (name, callback)->
		@sendRPC('room.join', [name], callback)

	# alias for ttapi compatibility
	roomRegister: (name, callback)->
		@joinRoom(name, callback)

	chat: (msg)->
		@send
			type: 'chat'
			msg: msg

	# alias for ttapi compatibility
	speak: (msg)->
		@chat msg

	upvote: (callback)->
		@sendRPC "room.cast", [true, @historyID, (@lastHistoryID == @historyID)], callback
		@lastHistoryID = @historyID

	downvote: (callback)->
		@sendRPC "room.cast", [false, @historyID, (@lastHistoryID == @historyID)], callback
		@lastHistoryID = @historyID

	woot: (callback)->
		@upvote(callback)

	meh: (callback)->
		@downvote(callback)

	vote: (updown, callback)->
		if (updown.toLowerCase() == "up")
			@upvote(callback)
		else
			@downvote(callback)

	changeRoomInfo: (name, description, callback)->
		roomInfo = 
			name: name
			description: description
		@sendRPC "moderate.update", roomInfo, callback

	changeRoomOptions: (boothLocked, waitListEnabled, maxPlays, maxDJs, callback)->
		if (!@roomId)
			throw new Error 'You must be in a room to change its options'
		options =
			boothLocked: boothLocked
			waitListEnabled: waitListEnabled
			maxPlays: maxPlays
			maxDJs: maxDJs
		@sendRPC "room.update_options", [@roomId, options], callback


module.exports = PlugAPI
