import arcpy
from arcpy import env
from arcpy.sa import *
import os
import traceback
import sys
import LegalGeo_Routines_Module
import shutil
import time


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

    project_folder = arcpy.GetParameterAsText(0)
    NewLRs = arcpy.GetParameterAsText(1)
    timeStamp = datetime.datetime.now().strftime('%Y%m%d%I%M')
    #arcpy.RefreshCatalog(project_folder)
    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"
	
    env.scratchWorkspace = env.workspace	
    env.overwriteOutput = 1
    lgRems = inPath+"lg_REMs"+imgExt
    env.snapRaster = lgRems
    env.extent = lgRems
    remDesc = arcpy.Describe(lgRems)
    cellSize = remDesc.meanCellWidth
    env.cellSize = cellSize
    lgRemsPrjOnly = inPath+"lg_remPrjOnly"+imgExt
    lgConvPrjOnly = inPath+"lg_ConvProjOnly"+imgExt 
    lrOnes = inPath+"lgLegal_LR_Ones"+imgExt
    LRs =inPath +"lgLegal_LRs"+imgExt
    
    lrs2Add = NewLRs.split(";")
    
        
    if len(lrs2Add) > 1: 
        NewLRsCombined = CellStatistics(lrs2Add,"MAXIMUM","DATA")
        NewLRsCombined.save("NewLRsCombined"+imgExt)
    #Don't know the numbers so making sure capture anything with value
        NewLRNull = IsNull("NewLRsCombined"+imgExt)
    else:
        inputPriority = lrs2Add[0]
        NewLRNull = IsNull(inputPriority)
    NewLRNull.save("NewLRNull"+imgExt)
    whereClause = '"VALUE" = 0'
    NewLRsOnes = Con("NewLRNull"+imgExt,"1","",whereClause)
    
    
    if arcpy.Exists(lrOnes):
        #copy old one and add to it
        #Need to add timeStamp
        arcpy.AddMessage("Updating current LR data.")
        NewLRsOnes.save("xxNewLRsOnes"+imgExt)
        arcpy.Copy_management(lrOnes, inPath+"lgLegal_LR_Ones"+timeStamp+imgExt)
        arcpy.Copy_management(LRs, inPath+"lgLegal_LRs"+timeStamp+imgExt)
        arcpy.Delete_management(lrOnes)
        arcpy.Delete_management(LRs)
        
        
        #arcpy.AddMessage("Creating new LR Ones Data.")
        toJoin = []
        toJoin.append(inPath+"lgLegal_LR_Ones"+timeStamp+imgExt)
        toJoin.append("xxNewLRsOnes"+imgExt)
        #arcpy.AddMessage("CellStats.")
        newCombinedlrOnes = CellStatistics(toJoin,"MAXIMUM","DATA") 
        #arcpy.AddMessage("Save.")
        newCombinedlrOnes.save(lrOnes)
        arcpy.AddMessage("Creating new LRs.")
        NewLRsRegGrp = RegionGroup(lrOnes,"EIGHT","WITHIN","NO_LINK") 
        NewLRsRegGrp.save(LRs)
    else:
        #create new one
        NewLRsOnes.save(lrOnes)
        NewLRsRegGrp = RegionGroup(NewLRsOnes,"EIGHT","WITHIN","NO_LINK")
        NewLRsRegGrp.save(LRs)
    
    
    times2 = Times(lrOnes,2)
    times2.save("times2"+imgExt)
    newRems = []
    newRems.append("times2"+imgExt)
    newRems.append(inPath+"lg_remPrjOnly"+imgExt)
    cRemsPrjOnly = CellStatistics(newRems,"SUM","DATA")
    cRemsPrjOnly.save("cRemsPrjOnly"+imgExt)
    whereClause = '"VALUE" = 1'
    finalRems = Con("cRemsPrjOnly"+imgExt,1,"",whereClause)
    arcpy.Copy_management(lgRemsPrjOnly, inPath+"lg_remPrjOnly"+timeStamp+imgExt)
    #Have overwrite ability within workspace
    finalRems.save(lgRemsPrjOnly)
    
    newConv = []
    newConv.append("times2"+imgExt)
    newConv.append(lgConvPrjOnly)
    cConv = CellStatistics(newConv,"SUM","DATA")
    cConv.save("cConv"+imgExt)
    whereClause = '"VALUE" = 1'
    finalCon = Con("cConv"+imgExt,1,"",whereClause)
    arcpy.Copy_management(lgConvPrjOnly,inPath+"lg_ConvProjOnly"+timeStamp+imgExt)
    #arcpy.Delete_management(
    finalCon.save(lgConvPrjOnly)
    
        
    
    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("Updated LRs " +str(datetime.datetime.now())+"\n")
    crs.write("LRs used in update: "+NewLRs+"\n")
    arcpy.AddMessage("LRs Added")
    arcpy.AddWarning("You will need to re-run Step 2 to create new landscape rankings and update LR data into database fully.")

finally:

    if arcpy.Exists(project_folder+"\\scratch"):
        try:
            arcpy.Delete_management(project_folder+"\\scratch")
        except:
            arcpy.AddWarning("Could not delete folder: "+project_folder+"\\scratch  Can be removed by user.")
      
    

	
	
