import arcpy
from arcpy import env
from arcpy.sa import *
#One of these imports causes the error with raster calculations using system type items like + * ect
#Requires saving files and using Raster("name")*num
import os
import traceback
import sys
import LegalGeo_Routines_Module

class LicenseError(Exception):
    pass
class DataMissing(Exception):
    pass

def isArcMap():
	try:
		arcpy.mapping.MapDocument("CURRENT")
		return True
	except:
		return False

    
try:
    #Check for spatial analyst license

    if arcpy.CheckExtension("Spatial") == "Available":
        arcpy.CheckOutExtension("Spatial")
    else:
        raise LicenseError

    #arcpy.AddMessage(outRasterName)

    project_folder = arcpy.GetParameterAsText(0)
    
    if arcpy.Exists(project_folder+"\\lg_input.gdb"):
        inPath = project_folder+"\\lg_input.gdb\\"
        inWS = project_folder+"\\lg_input.gdb"
        DirToRemove = project_folder+os.sep+"lg_scratch.gdb"
        if not(arcpy.Exists(project_folder+"\\lg_scratch.gdb")):
            arcpy.CreateFileGDB_management(project_folder,"lg_scratch.gdb")
        env.workspace = project_folder+"\\lg_scratch.gdb"
        outPath = project_folder+"\\lg_output.gdb\\"
        outWS = project_folder+"\\lg_output.gdb" #For adding to map view if user in ArcMap

        imgExt = ""
    else:
        inPath = project_folder+"\\lg_input\\"
        inWS = project_folder+"\\lg_input"
        if not(arcpy.Exists(project_folder+"\\lg_scratch")):
            arcpy.CreateFolder_management(project_folder,"lg_scratch")
        env.workspace = project_folder+"\\lg_scratch"
        outPath = project_folder+"\\lg_output\\"
        outWS = project_folder+"\\lg_output"
        DirToRemove = project_folder+os.sep+"lg_scratch"
        #arcpy.AddMessage(DirToRemove)
        imgExt=".img"    
    
    
    inRemRankingData = arcpy.GetParameterAsText(1)
    remRankDesc = arcpy.Describe(inRemRankingData)
    outRasterName = arcpy.GetParameterAsText(2)
    
    env.scratchWorkspace = env.workspace
    env.overwriteOutput = 1

    outRasterDataset = outPath+outRasterName+imgExt
    bndOnes = inPath+"lg_bnd_ones"+imgExt
    rems = inPath+"lg_REMs"+imgExt
    if arcpy.Exists(bndOnes) == False or arcpy.Exists(rems) == False:
        arcpy.AddError("Project input workspace missing data.")
        raise DataMissing
    
    
    clippedRems = Times(bndOnes,rems)
    clippedRems.save("clippedRems"+imgExt)
    
    #arcpy.Clip_management("lg_REMs"+imgExt,"#",clipRas,"lg_PrjBnd"+nameShpExt,"NoData","ClippingGeometry")

    
    #Analysis
    ZonalMeanRank = ZonalStatistics("clippedRems"+imgExt,"Value",inRemRankingData,"MEAN","DATA")
    ZonalMeanRank.save("xxlg_ZonalMeanRank"+imgExt)
    #clipRas = "xxlg_raster2Rank4WholeRem"+imgExt
    

    FinalFullRemSlice= LegalGeo_Routines_Module.rankAllVals("xxlg_ZonalMeanRank"+imgExt,"indvRem",imgExt)
    FinalFullRemSlice.save(outRasterDataset)

    inputFN = os.path.join(project_folder+os.sep,"lg_analysis_log.txt")
    if arcpy.Exists(inputFN):
        crs = open(inputFN,'a') 
    else:
        inputTxtFile = file(inputFN,'wt')
        crs = open(inputFN,'a')         
    crs.write("\n")
    crs.write("Step 2.1 Rank Individual Remnants ran on " +str(datetime.datetime.now())+"\n")
    crs.write("Remnant ranking file used: " + remRankDesc.catalogPath+"\n")
    crs.write("Output location:  "+outRasterDataset+"\n")  
    crs.write("*********Step 2.1: Individual Remnants Ranking End************\n")
    crs.write("\n")
    crs.close()    
    blnArcmap = isArcMap()
    if blnArcmap:
            #arcpy.MakeRasterLayer_management(arcpy.env.workspace+"\\"+outName,"rLayer")

    #workspaceLoc = arcpy.env.workspace
        descWorkspace = arcpy.Describe(outWS)
        if descWorkspace.workspaceType == "FileSystem":
            type = "RASTER_WORKSPACE"
        else:
            type = "FILEGDB_WORKSPACE"
        try:
            mxd = arcpy.mapping.MapDocument('CURRENT')
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            script_path=sys.argv[0]
            symb_dir = os.path.dirname(script_path) + '\\lyrfiles'
            lyr_symb = symb_dir + '\\WholeRemnantRankLandscape.lyr'
            newlayer1 = arcpy.mapping.Layer(lyr_symb)
            newlayer1.name = outRasterName
            newlayer1.replaceDataSource(outWS,type,outRasterName)
            arcpy.mapping.AddLayer(df, newlayer1, "TOP")
            arcpy.RefreshActiveView()
            arcpy.RefreshTOC()
        except:
            #nameLoc = arcpy.env.workspace+"\\"+outName
            arcpy.AddWarning("Could not create a layer in ArcMap for " +outRasterDataset)
            arcpy.AddWarning("You will need to add these data manually.")   
    

except LicenseError:
    arcpy.AddError ("Spatial Analyst license is unavailable") 	

except DataMissing:
    arcpy.AddError ("Select a different workspace or rerun LRSetup tool.")


except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value)
    arcpy.AddError(pymsg)
    
finally:
      
    arcpy.AddMessage("Cleaning up temporary files")
    LegalGeo_Routines_Module.deleteLGScratchFiles()
    
    