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 getWorldScriptsFromServer(self):
		scriptData[:] = []
		response = self.serverRequest('GET', '/api/v0.1/'+self.sessionKey+'/game/get/script-list/world_id='+self.currentWorldId)
		respString = response.read()
		serverScriptListing = respString.split('\n')
		# clear the script data array
		# extract script data from the response
		for listing in serverScriptListing:
			scriptInfo = listing.split('|')
			if scriptInfo[0] == "[W_SCRIPTLIST]":
				script = CScript(scriptInfo[1], scriptInfo[2])
				scriptData.append(script)
		return 1

	def getLocalCopyFromServer(self, script):
		response = self.serverRequest('GET', '/api/v0.1/'+self.sessionKey+'/game/get/script/world_id='+self.currentWorldId+'&script_id='+script.id+'&script_name='+script.name)
		respString = response.read()
		f = open(script.name.strip() + ',' + script.id.replace(':',',') + '.lua', 'w')
		f.write(respString)
		f.close()
		print 'Getting local copy from server! ' + script.name.strip() + '.lua'

	def serverRequest(self, command, url):
		self.conn.putrequest(command, url)
		self.conn.endheaders()
		return self.conn.getresponse()

	def getWorldScripts(self, username, password, worldName, directory):
		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.getWorldScriptsFromServer() == 0:
			print "Error getting world scripts"
			return 0
		os.chdir(directory)
		for item in scriptData:
			self.getLocalCopyFromServer(item)

def download(userName, password, worldName, destDirectory):
	mpConn.getWorldScripts(userName, password, worldName, destDirectory)
	print "Done."

mpConn = CMPServerConnection()
scriptData = []

def usage():
	print """
Usage: download [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
 -d directory          Directory to download scripts to
 --dir directory
	"""

def main(argv):
	username = ""
	password = ""
	worldname = ""
	destDirectory = os.getcwd()
	try:
		opts, args = getopt.getopt(argv, "u:p:w:d:", ["user=", "password=", "world=", "dir="])
	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 ("-d", "--dir"):
			destDirectory = arg
		else:
			print 'Unrecognized opt:' + opt + ' ' + arg
			usage()
	if (username == "") or (password == "") or (worldname == ""):
		usage()
	else:
		download(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()
"""

