import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import binascii
import time
import tinys3


def post_image_to_aws():
	S3_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' #YOU WILL NEED TO INPUT YOUR OWN S3 INFORMATION HERE
	S3_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' #YOU WILL NEED TO INPUT YOUR OWN S3 INFORMATION HERE

	my_bucket = 'sd.lockstars.com'
	my_file = 'victory.jpg'

	# Creating a simple connection
	conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,tls=True,endpoint='s3-us-west-2.amazonaws.com') #YOU WILL NEED TO INPUT YOUR OWN S3 INFORMATION HERE

	# Uploading a single file
	f = open(my_file,'rb')

	print conn.upload(my_file,f,my_bucket)
	print conn.get(my_file,my_bucket)
	
	f.close()


#the function for turning the hex text file into an image
def turn_to_image():
	global image_list
	nf = open("victory.jpg","wb")
	
	print "image list length = " + str(len(image_list))
	# turn hex data into binary for proper formatting into JPG
	for i in range(0, len(image_list)):
		for each in image_list[i]:
			nf.write(each) #function input requires even number of characters

	# Close the file
	nf.close()
	
	#reinitialize and clear image list
	image_list = []
	
	#post image to web server
	post_image_to_aws()
	



# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
	global image_list
	print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
	client.subscribe("LSPic", qos=0)
	client.subscribe("zimholte_test", qos=0)
	

	

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
	global image_list
	#print(msg.topic+" "+str(msg.payload))
	
	#zimholte_test message incoming
	#if (msg.topic == "zimholte_test"):
		#Publish a single message to a broker, then disconnect cleanly.
		
		#publish.single(topic="LSPic",payload="Herro", hostname="10.176.58.5", port=1883)
	
	#LSPic message incoming
	if(msg.topic == "LSPic"):
		print(msg.topic+" "+str(binascii.hexlify(msg.payload)))
		if ('ffd9' in str(binascii.hexlify(msg.payload))): # if it's the end of the photo, store it and close the file
			L = list(str(binascii.hexlify(msg.payload)))
			for i in range(0, len(L)):
				if ((L[i] == 'f') and (L[i+1] == 'f') and (L[i+2] == 'd') and (L[i+3] == '9')):
					image_list.append(list(binascii.a2b_hex('ffd9')))
					turn_to_image()
					#outputFile = open('photo_segments.txt', 'w')
					break
				else:
					image_list.append(L[i])
			
		else:
			#publish.single(topic="zimholte_test",payload="Prease", hostname="10.176.58.5", port=1883)
			image_list.append(list(str((msg.payload))))
	

#~#~#~#~#~#~#~#~#~#~#~#~#~ Begin Program ~#~#~#~#~#~#~#~#~#~#~#~#~#~#		

#list containing data for image
global image_list
image_list = []


#Create a client instance
client = mqtt.Client(client_id="python_client", clean_session=False, userdata=None, protocol='MQTTv311')
						##clean_session=False - the client is a durable client 
						#and subscription information and queued messages will 
						#be retained when the client disconnects
						##protocol=MQTTv311 can also be MQTTv31 presumably
						
						
client.on_connect = on_connect	#on_connect defined above 
client.on_message = on_message	#on_message defined above

#connect(host, port=1883, keepalive=60, bind_address="")
client.connect("10.176.58.5", 1883, 60)


# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()