import httplib
import urllib
import hashlib
import os
import time
import sys
import getopt
#from Tkinter import *

# class for holding script information
class CScript:
	id = "0:0"
	name = "dummy"
	def __init__(self, id, name):
		self.id = id
		self.name = name

class CMPServerConnection:
	HOSTNAME = 'alpha.metaplace.com'
	conn = httplib.HTTPSConnection(HOSTNAME)
	sessionKey = ""
	currentWorldId = ""

	def connect(self):
		self.conn.close()
		self.conn = httplib.HTTPSConnection(self.HOSTNAME)

	def getSessionKeyFromServer(self, username, password):
		passwd = hashlib.md5(password).hexdigest()
		response = self.serverRequest('GET', '/api/v0.1/public/game/get/session-id/username='+username+'&passwd='+passwd, '', '')
		respString = response.read().strip()
		data = respString.split('|')
		self.sessionKey = data[2]
		return 1
		
	def getWorldIdFromServer(self, worldname):
		response = self.serverRequest('GET', '/api/v0.1/'+self.sessionKey+'/game/get/world-name-service/name='+worldname, '', '')
		respString = response.read().strip()
		data = respString.split('|')
		if data[0] == "[S_WORLDLIST]":
			print "World ID:", data[1]
			self.currentWorldId = data[1]
		elif data[0] == "[S_WORLDSTATUS]":
			print respString
			if data[2] == "-1":
				print "World Currently Unavailable!"
			else:
				print "World is", data[2], ". Retry in", data[4]
				time.sleep(int(data[4])/1000)
				self.getWorldIdFromServer(worldname)
		else:
			print respString
		return 1
	
	def putWorldScriptOnServer(self, path):
		print "Putting script on server", path
		filename = path.split('\\')
		scriptInfo = filename[len(filename)-1].split(',')
		scriptName = scriptInfo[0]
		print 'ScriptName: ' + scriptName
		scriptId = scriptInfo[1] + ':' + scriptInfo[2].split('.')[0]
		print 'ScriptId: ' + scriptId
		# read the file
		f = open(path)
		fileContents = f.read()
		header = {"Content-type": "application/x-www-form-urlencoded",
					"Accept": "text/plain"}
		param = urllib.urlencode({'script': fileContents})
		response = self.serverRequest('POST', '/api/v0.1/777/game/put/script/world_id='+self.currentWorldId+'&script_id='+scriptId+'&script_name='+scriptName, param, header)
		respString = response.read()
		print respString

	def serverRequest(self, command, url, params, header):
		print params
		if header == '':
			self.conn.request(command, url, params)
		else:
			self.conn.request(command, url, params, header)
		#self.conn.endheaders()
		return self.conn.getresponse()

	def putWorldScript(self, username, password, worldName, filename):
		self.connect()
		if self.getSessionKeyFromServer(username, password) == 0:
			print "Error getting session key"
			return 0
		if self.getWorldIdFromServer(worldName) == 0:
			print "Error getting world Id"
			return 0
		if self.putWorldScriptOnServer(filename) == 0:
			print "Error posting world script"
			return 0

def upload(userName, password, worldName, filename):
	mpConn.putWorldScript(userName, password, worldName, filename)
	print "Done."

mpConn = CMPServerConnection()

def usage():
	print """
Usage: putScript [OPTIONS]
 -u username           Username to login with (required) 
 --user username
 -p password           Password for login (required)
 --password password
 -w worldname          Name of world to grab scripts from (required)
 --world worldname
 -f filename           Filename to upload (required)
 --file filename
	"""

def main(argv):
	username = ""
	password = ""
	worldname = ""
	destDirectory = os.getcwd()
	try:
		opts, args = getopt.getopt(argv, "u:p:w:f:", ["user=", "password=", "world=", "file="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("-u", "--user"):
			username = arg
		elif opt in ("-p", "--password"):
			password = arg
		elif opt in ("-w", "--world"):
			worldname = arg
		elif opt in ("-f", "--file"):
			destDirectory = arg
		else:
			print 'Unrecognized opt:' + opt + ' ' + arg
			usage()
			sys.exit(2)
	if (username == "") or (password == "") or (worldname == ""):
		usage()
	else:
		upload(username, password, worldname, destDirectory)

if __name__ == "__main__":
    main(sys.argv[1:])


"""
# root of the UI
root = Tk()
root.title('Metaplace Offline Script Tool')

	
def downloadScripts():
	# get the contents of the entry boxes
	worldName = worldNameEntry.get()
	userName = userNameEntry.get()
	password = passwordEntry.get()
	destDirectory = directoryEntry.get()
	
	# check for valid entries
	if worldName == "":
		print "Must supply a world name!"
	elif userName == "":
		print "Must supply a user name!"
	elif password == "":
		print "Must supply a password!"
	else:
		# get data from the server
		mpConn.getWorldScripts(userName, password, worldName, destDirectory)
		print "Done."

worldNameLabel = Label(root, text="World Name:")
worldNameLabel.pack({"side": "top"})

worldNameEntry = Entry(root)
worldNameEntry.pack({"side": "top"})

worldNameEntry.delete(0, END)

userNameLabel = Label(root, text="Username:")
userNameLabel.pack({"side": "top"})

userNameEntry = Entry(root)
userNameEntry.pack({"side": "top"})

userNameEntry.delete(0, END)

passwordLabel = Label(root, text="Password:")
passwordLabel.pack({"side":"top"})

passwordEntry = Entry(root, show="*")
passwordEntry.pack({"side":"top"})
passwordEntry.delete(0, END)

directoryLabel = Label(root, text="Editor:")
directoryLabel.pack({"side":"top"})

directoryEntry = Entry(root)
directoryEntry.pack({"side":"top"})
directoryEntry.delete(0, END)

editScriptButton = Button(root, text="Download Scripts", command=downloadScripts)
editScriptButton.pack({"side": "top"})

root.mainloop()
"""

