import arcrest, urllib, zipfile, os, datetime
from arcrest import manageorg

##User Assigned Variables:
baseURL = arcpy.GetParameterAsText(0) #"http://esridot.maps.arcgis.com"
tokenURL = arcpy.GetParameterAsText(1) #None
username = arcpy.GetParameterAsText(2) #"DOT_erodenberg"
pw = arcpy.GetParameterAsText(3) #"mapmaker"
CADservice = arcpy.GetParameterAsText(4) #"SV_64121_5c033081"
fgdbExport = arcpy.GetParameterAsText(5) #r"D:\Data\Data_Customer\AlaskaDOT\CAD_Updates"
OutFormat = arcpy.GetParameterAsText(6) #"DWG_R2010"
seedFile = arcpy.GetParameterAsText(7)

##Defined Variables:
CAD_Name = CADservice.split('_')[1] + "_SV"
directory = fgdbExport + "\\" + CAD_Name
sharingURL = baseURL + "/sharing/rest" 
fgdbDownload = directory + "\\" + CAD_Name + '.zip'

#GeoProessing Task Logic

# Make project directory
if not os.path.exists(directory):
    os.makedirs(directory)
# Login to ArcGIS Online and get a token.    
if tokenURL and tokenURL.strip():
    arcpy.AddMessage(tokenURL)
    sh = arcrest.AGOLTokenSecurityHandler(username, pw, tokenURL)
    arcpy.AddMessage("Logging into Portal for ArcGIS with a token")
else:
    sh = arcrest.AGOLTokenSecurityHandler(username, pw)
    arcpy.AddMessage("Logging into ArcGIS Online")
    # Connect to AGOL
    org = manageorg.Administration(url=sharingURL, securityHandler=sh)
    result = org.query(q=CADservice.replace(" ",""),bbox=None)
    keyset = ['results']
    
    #Get the Feature Service Name and it's ItemID
    value = None
    for key in keyset:
        if key in result:
            value = result[key]
            arcpy.AddMessage("Logged into ArcGIS Online as " + username + " " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y"))
            arcpy.AddMessage("Searching for: " + CADservice + " Feature Service")
            if (value == []):
                arcpy.AddMessage("The " + CADservice.replace(" ","") + " Feature Service could not be found.")
            else:
                existingTitles = [d['title'] for d in value]
                existingIDs =[d['id'] for d in value]
                existingTypes =[d['type'] for d in value]
                dictionary = dict(zip(existingTypes, existingIDs))
                #Launch Export and download routine...
                arcpy.AddMessage("Found " + CADservice + " Feature Service")
                if "Feature Service" in dictionary:
                    fsID = dictionary['Feature Service']
                    content = org.content
                    item = content.item(fsID)
                    usercontent = content.usercontent(username)
                    result = usercontent.exportItem(title=CADservice, itemId=fsID, exportFormat="File Geodatabase")
                    exportedItemId = result['exportItemId']
                    jobId = result['jobId']
                    exportItem = content.item(itemId=exportedItemId)
                    # Ensure the item is finished exporting before downloading
                    status =  usercontent.status(itemId=exportedItemId, jobId=jobId, jobType="export")
                    arcpy.AddMessage("Exporting Feature Service as a File Geodatabase")
                    arcpy.AddMessage(status)
                    while status['status'].lower() == "processing":
                        time.sleep(3)
                        arcpy.AddMessage(status)
                        status =  usercontent.status(itemId=exportedItemId,
                                                     jobId=jobId,
                                                     jobType="export")
                    token = sh.token
                    arcpy.AddMessage("Downloading File Geodatabase as a Zip File")                    
                    url = baseURL + "/sharing/rest/content/items/" + exportedItemId + "/data?token=" + token + "&f=json"
                    response = urllib.urlretrieve(url, fgdbDownload)
                    arcpy.AddMessage("Downloading Complete")
                                    
                    #Extract Geodatabase from Zipfile.
                    arcpy.AddMessage("Exracting Zip File")
                    with zipfile.ZipFile(fgdbDownload, "r") as z:
                        z.extractall(directory + "\\")
                    
                    #Rename file Geodatabase    
                    arcpy.AddMessage("Renaming File Geodatabase to " + CAD_Name + ".gdb")
                    #List all Geodatabases in the Workspace
                    arcpy.env.workspace = directory
                    workspaces = arcpy.ListWorkspaces("*", "FileGDB")
                    for workspace in workspaces:
                        arcpy.Rename_management(workspace, CAD_Name + ".gdb")
                    
                    #Export to AutoCAD                
                    arcpy.env.workspace = directory + "\\" + CAD_Name + ".gdb"
                    arcpy.AddMessage("Exporting to " + CAD_Name + "." + OutFormat.split("_")[0])
                    outCAD = directory + "\\" + CAD_Name + "." + OutFormat.split("_")[0]
                    arcpy.ExportCAD_conversion(["Polygon","Polyline","Point"],OutFormat, outCAD, "IGNORE_FILENAMES_IN_TABLES", "OVERWRITE_EXISTING_FILES", seedFile)
                    
                    #Delete AGOL File GDB export item.
                    arcpy.SetParameter(1, True)
                    delResults =  usercontent.deleteItems(items=exportedItemId)
                    response = delResults['results'].pop(-1)
                    status = response['success']
                    arcpy.AddMessage("Export completed Successfully!")