import arcpy
from arcpy import env
from arcpy.sa import *
import os
import traceback
import sys
import math
import LegalGeo_Routines_Module

class LicenseError(Exception):
    pass


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

def returnArea(areaUnits,outUnit,cellSize,NumCells):
    area_units = areaUnits.split()
    count = len(area_units)
    #num = area_units[0]
    units = area_units[1]
    if units == "Square"+outUnit:
        area = NumCells*cellSize*cellSize 
    else:
        if outUnit == "Feet":
            if units == "SquareMiles":
                    cvFact = 27880000
            elif units == "SquareMeters":
                    cvFact = 10.7639
            elif units == "SquareKilometers":
                    cvFact = 10760000
            elif units == "Acres":
                cvFact = 43560
            elif units == "Hectares":
                cvFact = 107639
        else:
            if units == "SquareMiles":
                    cvFact = 2590000
            elif units == "SquareFeet":
                    cvFact = 0.092903
            elif units == "SquareKilometers":
                    cvFact = 1000000
            elif units == "Acres":
                cvFact = 4046.86
            elif units == "Hectares":
                cvFact = 10000
        #returnVal = (float(num)*cvFact)/(cellSize*cellSize)        
        area = NumCells*cellSize*cellSize/cvFact       
    finalString = str(area) +" "+ units
    return finalString
    
def returnCellCount(areaUnits,outUnit,cellSize):
    area_units = areaUnits.split()
    count = len(area_units)
    num = area_units[0]
    units = area_units[1]
    if units == "Square"+outUnit:
        out = float(num) /(cellSize*cellSize) 
        return out
    else:
        if outUnit == "Feet":
            if units == "SquareMiles":
                    cvFact = 27880000
            elif units == "SquareMeters":
                    cvFact = 10.7639
            elif units == "SquareKilometers":
                    cvFact = 10760000
            elif units == "Acres":
                cvFact = 43560
            elif units == "Hectares":
                cvFact = 107639
        else:
            if units == "SquareMiles":
                    cvFact = 2590000
            elif units == "SquareFeet":
                    cvFact = 0.092903
            elif units == "SquareKilometers":
                    cvFact = 1000000
            elif units == "Acres":
                cvFact = 4046.86
            elif units == "Hectares":
                cvFact = 10000
        returnVal = (float(num)*cvFact)/(cellSize*cellSize)        
                
        return returnVal
        
try:

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

    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 = ""
        tabExt=""
    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"
        tabExt=".dbf"
    
    env.scratchWorkspace = env.workspace
    regenRLyrName = arcpy.GetParameterAsText(1)
    regRankDesc = arcpy.Describe(regenRLyrName)

    areaUnits = arcpy.GetParameterAsText(2)
    outName = arcpy.GetParameterAsText(3)


    regenImgDesc = arcpy.Describe(regenRLyrName)
    outUnit = regenImgDesc.spatialReference.linearUnitName
    cellSize = Raster(regenRLyrName).meanCellWidth    
    
    
    

    arcpy.env.overwriteOutput = 1

    
    outNameDataset = outPath+outName+imgExt
    
    cellsNeeded = returnCellCount(areaUnits,outUnit,cellSize)
    arcpy.Statistics_analysis(regenRLyrName,"clip_Statistics"+tabExt,"Count SUM","#")
    toDelete.append("clip_Statistics"+tabExt)
    statRows = arcpy.SearchCursor("clip_Statistics"+tabExt)
    for rowNeeded in statRows:
        totalCellsinClipRaster = rowNeeded.getValue("SUM_Count")
        #arcpy.AddMessage(str(totalCellsinClipRaster) + " total cells in raster")
    TargetNum = totalCellsinClipRaster - cellsNeeded
    currentNum = 0  
    finalNum = 0    
    arcpy.BuildRasterAttributeTable_management(regenRLyrName, "Overwrite")
    rasterRows = arcpy.SearchCursor(regenRLyrName)
    for rasRow in rasterRows:
        val = rasRow.getValue("Value")
        count = rasRow.getValue("Count")
        currentNum = currentNum+count
        if currentNum > TargetNum:
            break
        else:
            finalNum = totalCellsinClipRaster - currentNum + count
            
    whereClause = "Value >= "+str(val)
    conRaster = Con(regenRLyrName,1,"",whereClause)
    conRaster.save(outNameDataset)
    #finalOutRaster = SetNull("conRaster"+imgExt,"conRaster"+imgExt,"Value <> 1")
    #finalOutRaster.save(outNameDataset)
    strTotal = returnArea(areaUnits,outUnit,cellSize,finalNum)
    arcpy.AddMessage ("A total of "+strTotal+" were identified.") 

    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 3.1 Regeneration Landscape-level Priority ran on " +str(datetime.datetime.now())+"\n")
    crs.write("Regeneration ranking file used: " + regRankDesc.catalogPath+"\n")
    crs.write("Area requirement = " +areaUnits+"\n")
    crs.write("Output location:  "+outNameDataset+"\n")  
    crs.write("*********Step 3.1: Regeneration Landscape-level Priority Ranking************\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 + '\\ParcelRegenLoc.lyr'
            newlayer1 = arcpy.mapping.Layer(lyr_symb)
            newlayer1.name = outName
            newlayer1.replaceDataSource(outWS,type,outName)
            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 " +outNameDataset)
            arcpy.AddWarning("You will need to add these data manually.")  
            

   

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




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()
		 