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

class LicenseError(Exception):
    pass


class DataMissing(Exception):
    pass


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

def runAnalysis(regenLayer,clipPoly,outName,imgExt):    
    try:
        arcpy.Clip_management(regenRLyrName,"#","clip"+imgExt,clipPoly,"NoData","ClippingGeometry")    
        finalOutRaster  = Con("clip"+imgExt,1)
        finalOutRaster.save(outName)
        
            
        blnArcmap = isArcMap()
        if blnArcmap:
            workspaceLoc = arcpy.env.workspace
            descWorkspace = arcpy.Describe(workspaceLoc)
            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 + '\\ParcelAllowLR.lyr'
                newlayer1 = arcpy.mapping.Layer(lyr_symb)
                newlayer1.replaceDataSource(workspaceLoc,type,outName)
                newlayer1.name = 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.") 
                #pass
            #arcpy.ApplySymbologyFromLayer_management (newlayer1, lyr_symb)


    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)

        

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

    parcelLyrName = arcpy.GetParameterAsText(0)
    #uIDfld = arcpy.GetParameterAsText(1)
    #haFieldName = arcpy.GetParameterAsText(2)
    regenRLyrName = arcpy.GetParameterAsText(1)
    outWorkspace = arcpy.GetParameterAsText(2)
    rasterName = arcpy.GetParameterAsText(3)

    arcpy.env.overwriteOutput = 1
    wsDesc = arcpy.Describe(outWorkspace)   

    if wsDesc.workspaceType == "FileSystem":
        imgExt =".img"
        tabExt = ".dbf"
        shpExt=".shp"

        
#Getting cargio workspace --------------

 
    
    arcpy.env.outputCoordinateSystem = regenRLyrName
    arcpy.env.workspace = outWorkspace
    arcpy.env.scratchWorkspace = outWorkspace
   
    
    arcpy.CopyFeatures_management(parcelLyrName,"regenParcelsAnalyzed"+shpExt)
    toDelete.append("regenParcelsAnalyzed"+shpExt)
    arcpy.MakeFeatureLayer_management("regenParcelsAnalyzed"+shpExt,"Parcels4Analysis")
    toDelete.append("Parcels4Analysis")
    env.mask = "Parcels4Analysis"
    conOut = Con(regenRLyrName,1,"","Value > 0")
    outName = rasterName+imgExt
    conOut.save(outName)

    blnArcmap = isArcMap()
    if blnArcmap:
        workspaceLoc = arcpy.env.workspace
        descWorkspace = arcpy.Describe(workspaceLoc)
        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 + '\\ParcelAllowLR.lyr'
            newlayer1 = arcpy.mapping.Layer(lyr_symb)
            newlayer1.replaceDataSource(workspaceLoc,type,outName)
            newlayer1.name = 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.") 
    
#    totalCount = int(arcpy.GetCount_management("Parcels4Analysis").getOutput(0))
#    desc4Analysis = arcpy.Describe("Parcels4Analysis")
#    shpFieldName = desc4Analysis.ShapeFieldName
#    calculatingParcel = 1
#    parcelsWORecords = 0   
    
#    i=0
#    for row in arcpy.da.SearchCursor("Parcels4Analysis",("SHAPE@",uIDfld)):
#        i+=1
#        poly = row[0]
#        parcelID = row[1]
#        if parcelID is None:
#            arcpy.AddWarning("Row "+str(i)+ " is missing an id value.  It will be skipped")
#            parcelsWORecords = parcelsWORecords+1
#            continue
        
#        name4output = "Parcel_"+str(parcelID)+"_LR_Remain"+imgExt
#       runAnalysis(regenRLyrName,poly,name4output,imgExt)

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


except DataMissing:
    arcpy.AddError ("Data Input Error.")


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("Removing Temporary Files.")
    if arcpy.Exists("Parcels4Analysis"):
        arcpy.Delete_management("Parcels4Analysis")
    if arcpy.Exists("regenParcelsAnalyzed"+shpExt):
        arcpy.Delete_management("regenParcelsAnalyzed"+shpExt)
    arcpy.AddMessage("Analysis Finished!")
    #arcpy.AddMessage("Data found in selected output workspace:  "+outWorkspace)
