#!/usr/bin/env python

import base64
import urllib
import urllib2
import xml.etree.ElementTree as ET
import os
import time
import sys, traceback
import oauth2 as oauth
import pdb
import httplib2

## Grab the various keys and secrets from the config file
Config_File = "Twi_X10.conf"
ConfigFile = open(Config_File, "r")
Access_key = ConfigFile.readline()[:-1]
Access_key_secret = ConfigFile.readline()[:-1]
Consumer_key = ConfigFile.readline()[:-1]
Consumer_key_secret = ConfigFile.readline()[:-1]
ConfigFile.close()

## Grab the allowed users from the users config file
Allowed_User_File = "Twi_X10_Users.conf"
AllowedUserFile = open(Allowed_User_File, "r")
allowed_users = set()
for user in AllowedUserFile:
	allowed_users.add(user[:-1])
AllowedUserFile.close()

## These are the files that will be opened if logging is turned on (see below)
Exception_Log_File = "exceptions"
Tweet_Log_File = "Tweets"

## This sets up the oauth communication with Twitter
token = oauth.Token(key=Access_key, secret=Access_key_secret)
consumer = oauth.Consumer(key=Consumer_key, secret=Consumer_key_secret)

client = oauth.Client(consumer, token, timeout=10)

## This keeps track of the last (direct) message that was received/acted upon
last_message_id = long(0)

## These turn on logging and whether or not information should be written to the screen
## The files that will be used are configurable above
info_mode = True
log_exceptions = True
log_Tweets = False

## These variables keep information for exception handling
previous_exception = ["", ""]
exception_count = 0

## This keeps track of the program location for debugging purposes
program_location = 0

while True:
	try:
		program_location = 1
		response, content = client.request("http://api.twitter.com/1/direct_messages.xml?count=1", "GET")
		program_location = 2

		if info_mode == True:
			os.system("clear")
			print "Current Time: " + time.asctime()

		if response.status == 200:
			program_location = 3
			tree = ET.fromstring(content)

			command_tag = tree.find("direct_message/text")
			command = command_tag.text
			screen_name_tag = tree.find("direct_message/sender_screen_name")
			screen_name = screen_name_tag.text
			current_message_id_tag = tree.find("direct_message/id")
			current_message_id = long(current_message_id_tag.text)
			message_date_tag = tree.find("direct_message/created_at")
			message_date = message_date_tag.text

			if info_mode == True:
				print "===== Message information ====="
				print "Message id: " + str(current_message_id)
				print "Last id: " + str(last_message_id)
				print "Sender Screen Name: " + screen_name
				print "Message Text: " + command
				print "Message Timestamp: " + message_date
				print "===== Parsing information ====="

			program_location = 4
			parsed_command = command.split(";")
			parsed_command = parsed_command[0].split("&")

			if current_message_id == last_message_id:
				if info_mode == True:
					print "Message already processed"
			elif parsed_command[0] != "x10":
				if info_mode == True:
					print "No \"x10\" found!"
			elif screen_name not in allowed_users:
				if info_mode == True:
					print "User not allowed"
			elif parsed_command[0] == "x10" and current_message_id > last_message_id and screen_name in allowed_users:
				heyu_status = os.system("heyu " + parsed_command[1])
				last_message_id = current_message_id
				data_to_add = time.asctime() + ": " + parsed_command[1] + " from " + screen_name + ", status: "
				if heyu_status == 0:
					data_to_add += "OK"
				else:
					data_to_add += str(heyu_status)
				print data_to_add
				program_location = 5


				if info_mode == True:
					print "x10 command: " + parsed_command[1]
					print "Time: " + time.asctime()
					print "Tweet: " + data_to_add
					print "Username: " + screen_name
					print "Heyu response: " + str(heyu_status)

				if log_Tweets == True:
					Tweet_Log = open(Tweet_Log_File, "a")
					Tweet_Log.write("x10 command: " + parsed_command[1] + "\n")
					Tweet_Log.write("Time: " + time.asctime() + "\n")
					Tweet_Log.write("Tweet: " + post.get_data() + "\n")
					Tweet_Log.write("Username: " + screen_name + "\n")
					Tweet_Log.write("Heyu response: " + str(heyu_status) + "\n\n")
					Tweet_Log.close()

				program_location = 6
				response, content = client.request("http://api.twitter.com/1/statuses/update.xml", method="POST", body=urllib.urlencode({'status': data_to_add}))
				program_location = 7

			time.sleep(1)
		else:
			if info_mode == True:
				print "===== Response Error ====="
				print "Response status: " + str(response.status)
				print "Time: " + time.asctime()

			time.sleep(10)

	except httplib2.ServerNotFoundError:
		if info_mode == True:
			print "Exception: " + str(sys.exc_info()[0]) + ":" + str(sys.exc_info()[1])

		sys.exc_clear
		time.sleep(10)
	except KeyboardInterrupt:
		sys.exit(0)
	except:
		if log_exceptions == True:
			Exception_Log = open(Exception_Log_File, "a")
			Exception_Log.write("\nAn exception has occurred\n")
			Exception_Log.write("Current Time is: " + time.asctime() + "\n")
			if response.status == 200:
				Exception_Log.write("Last tweet was: " + command + "\n")
				Exception_Log.write("Sent by: " + screen_name + "\n")
				Exception_Log.write("Exception: " + str(sys.exc_info()[0]) + ":" + str(sys.exc_info()[1]) + "\n")
			else:
				Exception_Log.write("Response status: " + str(response.status) + "\n")
				Exception_Log.write("Response: " + str(response) + "\n")
				Exception_Log.write("Content: " + str(content) + "\n")
			Exception_Log.close()

		if info_mode == True:
			print "Exception: " + str(sys.exc_info()[0]) + ":" + str(sys.exc_info()[1])

		if previous_exception[0] == sys.exc_info()[0] and previous_exception[1] == sys.exc_info()[1]:
			exception_count += 1
		else:
			exception_count = 0
			previous_exception[0] = sys.exc_info()[0]
			previous_exception[1] = sys.exc_info()[1]

		pdb.set_trace()

		sys.exc_clear
		time.sleep(1)
