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

def isArcMap():
	try:
		arcpy.mapping.MapDocument("CURRENT")
		return True
	except:
		return False
	
try:
    indvParcelLayer = arcpy.GetParameterAsText(0)
    LandscapeRanking = arcpy.GetParameterAsText(1)
    arcpy.env.overwriteOutput = 1
    regenParcelDesc = arcpy.Describe(indvParcelLayer)
    workspace = regenParcelDesc.path
    arcpy.env.workspace = workspace
    arcpy.env.scratchWorkspace = workspace
    wsDesc = arcpy.Describe(workspace)

    names = indvParcelLayer.split("_")
    if len(names)== 4:
        outName =names[0]+"_"+names[1]+"_"+names[2]+"_RankZones"
    else:
        if "." in indvParcelLayer:
            newNames = indvParcelLayer.split(".")
            outName = newNames[0]+"_RankZones"
        else:
            outName = indvParcelLayer+"_RankZones"
    imgExt =""
    type = "FILEGDB_WORKSPACE"
    if wsDesc.workspaceType == "FileSystem":
        imgExt =".img"
        type = "RASTER_WORKSPACE"
        
# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "RegenPriorities_Parcel844"

    whereClause = "Value = 1"
    conOut = Con(indvParcelLayer,1,"",whereClause)

    rGroup = RegionGroup(conOut,"EIGHT","WITHIN","NO_LINK","#")
# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "RegionG_Rege1", "Regen_Clip"
    zonalR = ZonalStatistics(rGroup,"Value",LandscapeRanking,"SUM","DATA")
    #zonalR.save("zonalTmp"+imgExt)
    zonalRInt = Int(zonalR)
    #zonalRInt.save("intTmp"+imgExt)
    arcpy.BuildRasterAttributeTable_management(zonalRInt, "Overwrite")
    totalCount = int(arcpy.GetCount_management(zonalRInt).getOutput(0))
    outSlice = Slice(zonalRInt,totalCount,"NATURAL_BREAKS","1")
    val = totalCount+1
    rasterMinus = Minus(outSlice,val)
    finalScore = Times (rasterMinus,-1)
    finalScore.save(outName+imgExt)

    blnArcmap = isArcMap()
    if blnArcmap:
       # arcpy.MakeRasterLayer_management(arcpy.env.workspace+"\\"+outName,"rLayer")
        workspaceLoc = arcpy.env.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 + '\\ParcelAllocZones.lyr'

            newlayer1 = arcpy.mapping.Layer(lyr_symb)
            newlayer1.name = outName
            newlayer1.replaceDataSource(workspaceLoc,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 " +nameLoc)
            arcpy.AddWarning("You will need to add these data manually.") 




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("Analysis Finished!")
    #arcpy.AddMessage(outName + " found in selected output workspace:  "+workspace)
       