#import pycurl
import xmltodict
#from StringIO import StringIO
import subprocess
import os
import requests

#Get Python Location
pathtopython = "c:\\python27\\python.exe"
try:
    pathtopython = os.getenv('ARDIPythonPath')
except:
    pass

def translatedriver(drv):    
    return ""

def launchdriver(drivers,portcode):
    #print "Launching Driver " + drivers + " / " + portcode
    drv = translatedriver(drivers)
    if (drv == ""):
        drv = drivers + "/" + drivers + ".py"
    scriptname = os.getcwd() + "/" + drv
    print(pathtopython + " " + scriptname)
    subprocess.Popen([pathtopython, scriptname, portcode], stdout=None, stdin=None, shell=False,stderr=None,close_fds=True)

def parseconfig(xml):
    result = xmltodict.parse(xml)
                        
    #Core Parameters
    if '@port' in result['launcherdata']['driver']:
        portcode = result['launcherdata']['driver']['@port']
        driver = result['launcherdata']['driver']['@driver']
        launchdriver(driver, portcode)
    else:
        for itm in result['launcherdata']['driver']:
           portcode = itm['@port']
           driver = itm['@driver']
           launchdriver(driver, portcode)

#response = StringIO()
servername = "localhost"
        
fullurl = "http://" + servername + "/api/launcherdriver.php"
        
#c = pycurl.Curl()
#c.setopt(c.URL,fullurl)
#c.setopt(c.WRITEFUNCTION,response.write)
#c.setopt(c.TIMEOUT,5)
#c.setopt(c.CONNECTTIMEOUT,5)
#c.perform()
#c.close()
resp = requests.get(fullurl)
        
parseconfig(resp.text)
