# import required modules...
import arcpy
from arcpy import env
from arcpy.sa import *
import os
import time
import traceback
import sys
#import tempfile
import math
import LegalGeo_Routines_Module


def BiodiversityRank(Rem_ZI_Dist,inPath,outPath,crs):
    try:
		ws = arcpy.env.workspace
		wsDesc = arcpy.Describe(ws)
		tabExt=""
		nameShpExt=""
		imgExt=""
		if wsDesc.workspaceType == "FileSystem":
			nameShpExt=".shp"
			imgExt =".img"
			tabExt =".dbf"

		lgOnes = inPath+"lg_REM_Ones"+imgExt
		lgRems = inPath+"lg_REMs"+imgExt
		lgBio_NatVeg = inPath+"lgBio_NatVeg"+imgExt
		lgBio_NatVegRank = inPath+"lgBio_NatVegUserRank"+imgExt
		lgBio_OtherRank = inPath+"lgBio_NatVegOtherRank"+imgExt

		lgRemsPrjOnly = inPath+"lg_remPrjOnly"+imgExt
		lgConvPrjOnly = inPath+"lg_ConvProjOnly"+imgExt 

		natVegRasters2Sum= []    
			

		#Richness********************************************************
		arcpy.AddMessage("-->Runnning Vegetative Richness analysis")

		Richness = ZonalStatistics(lgRems,"VALUE",lgBio_NatVeg,"VARIETY","DATA")
		Richness.save("xxlg_VegRichness"+imgExt)
		RichRemOnly = Times("xxlg_VegRichness"+imgExt,lgRemsPrjOnly)
		RichRemOnly.save("xxlg_VegRichPrjOnly"+imgExt)
		#Applying Natural breaks causes values to be compressed to ranking with increments of one
		#Equal interval applies a strecth of these values with lowest equal to 1 and highest equal to 100 however values of say 8,10 (ie 9 skipped) would be ranked
		#roughly 80, 100 vs 90,100
		RichnessRank = Slice("xxlg_VegRichPrjOnly"+imgExt,100,"Equal_Interval",1)
		#RichnessSlice.save("xxlg_VegRichnessSlice"+imgExt)
		#RichnessRank = LegalGeo_Routines_Module.scaleUp("xxlg_VegRichnessSlice"+imgExt,100)
		RichnessRank.save(outPath+"lgBio_RichnessRank"+imgExt)    
		natVegRasters2Sum.append(outPath+"lgBio_RichnessRank"+imgExt)
		crs.write("Richness Layer:  "+"lgBio_RichnessRank"+imgExt)
		crs.write("\n")
		#Richness Completed***********************************************

		#Shannon Index ****************************************************
		arcpy.AddMessage("-->Runnning Shannon Index analysis")
		calcValsTab = "xxlg_siTable"+tabExt

		TabulateArea(lgRems,"VALUE",lgBio_NatVeg,"VALUE",calcValsTab)

		flds2use =[]
		fldNums=[]
		flds = arcpy.ListFields(calcValsTab)
		fldCount = 0
		for fld in flds:
			if fldCount > 1:
				flds2use.append(fld.name)
				fldNums.append(fldCount)
			fldCount = fldCount+1
		#print flds2use

		joinFld = flds[1]
		#print joinFld


		arcpy.AddField_management(calcValsTab,"Total_Cnt","DOUBLE")
		arcpy.AddField_management(calcValsTab,"si","DOUBLE")
		fldNum4SI = fldCount+1  #only one due to fldcount is added at the end of the loop above

		# 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: "siTable"
		calcString4sum =""
		for fldname in flds2use:
			calcString4sum = calcString4sum+"["+fldname+"] + "

		finalCalcString = calcString4sum[:-3]
		#print finalCalcString


		arcpy.CalculateField_management(calcValsTab,"Total_Cnt",finalCalcString,"VB","#")

		#newFldList = arcpy.ListFields(calcValsTab)
		with arcpy.da.UpdateCursor(calcValsTab,"*") as updateCursor:
			for row in updateCursor:
				#row = updateCursor.next()
				#print row
				totalArea = row[fldCount]
				#print totalArea
				totalSI = 0
				for num in fldNums:
					val = row[num]
					#print val
					#print float(val)/float(totalArea)
					if val >0:
						proportion = val/totalArea
						#print proportion
						siContribution = proportion * math.log(proportion)
						#print siContribution
						totalSI = totalSI+siContribution
				
				#print totalSI
				finalVal = totalSI*-1
				row[fldNum4SI] = finalVal
				updateCursor.updateRow(row)

		del row
		del updateCursor
		ext = env.extent
		env.extent = "MAXOF"
		arcpy.MakeTableView_management(calcValsTab,"joinTab")

		remRasterLayer = "Lyr_lg_REMs"
		arcpy.MakeRasterLayer_management(lgRems,remRasterLayer)
		#arcpy.AddMessage("Here it dies")
		#need to join raster with table
		arcpy.AddJoin_management(remRasterLayer,"Value","joinTab","VALUE","KEEP_ALL")        
		#arcpy.AddMessage("Now Lookup")
		#run lookup using field siTable.VALUE	
		siRaster = Lookup(remRasterLayer,"xxlg_siTable.si")
		siRaster.save("xxlg_siRaster"+imgExt)
		env.extent = ext 
		siRemOnly = Times(lgRemsPrjOnly,"xxlg_siRaster"+imgExt)
		#conSIRaster = Con("xxlg_siRaster"+imgExt,"xxlg_siRaster"+imgExt,"","VALUE >= 0")
		siRemOnly.save("xxlg_siRemOnly"+imgExt)


		siSlice = Slice("xxlg_siRemOnly"+imgExt,100,"NATURAL_BREAKS",1)
		siSlice.save("xxlg_siSlice"+imgExt)
		#HERE for note 1 with Marcelo*******
		#Seems like errors come up when trying to use the remove join in different ArcGIS versions.
		try:
			arcpy.RemoveJoin_management(remRasterLayer)
		except:
			pass
		  
		siRanking = LegalGeo_Routines_Module.scaleUp("xxlg_siSlice"+imgExt,100)
		siRanking.save(outPath+"lgBio_SiRank"+imgExt)
		natVegRasters2Sum.append(outPath+"lgBio_SiRank"+imgExt)
		crs.write("Diversity Layer:  "+"lgBio_SiRank"+imgExt)
		crs.write("\n")
			
		#Ranking based on user ranked values************************
		if arcpy.Exists(lgBio_NatVegRank):
			arcpy.AddMessage("-->Runnning Vegetative user rank analysis")

			#If user ranks by 100 vals kept as is
			rasterObj = Raster(lgBio_NatVegRank)
			max = rasterObj.maximum
			if max == 100:
				NVRankRemsOnly = Times(lgRemsPrjOnly,lgBio_NatVegRank)
				NVRankRemsOnly.save(outPath+"lgBio_VegRank"+imgExt)
			else:   
				#Using EI since data is already ranking remnants.
				natVegSlice = Slice(lgBio_NatVegRank,100,"EQUAL_INTERVAL",1)
				natVegSlice.save("xNatVegSlice"+imgExt)
				NVRankRemsOnly = Times(lgRemsPrjOnly,"xNatVegSlice"+imgExt)
				NVRankRemsOnly.save(outPath+"lgBio_VegRank"+imgExt)
				
			natVegRasters2Sum.append(outPath+"lgBio_VegRank"+imgExt)
			crs.write("Rarity Layer:  lgBio_VegRank"+imgExt)
			crs.write("\n")
		#Rank other********************************************** 
		if arcpy.Exists(lgBio_OtherRank):
			arcpy.AddMessage("-->Runnning Other Vegetation Metric")
			#If user ranks by 100 vals kept as is
			rasterObj = Raster(lgBio_OtherRank)
			max = rasterObj.maximum
			if max == 100:
				BioOtherRemsOnly = Times(lgRemsPrjOnly,lgBio_OtherRank)
				BioOtherRemsOnly.save(outPath+"lgBio_OtherRank"+imgExt)
			else:             
			#Using EI since data is already ranking remnants...
				natVegSlice = Slice(lgBio_OtherRank,100,"EQUAL_INTERVAL",1)
				natVegSlice.save("xBioOtherSlice"+imgExt)
				BioOtherRemsOnly = Times(lgRemsPrjOnly,"xBioOtherSlice"+imgExt)
				BioOtherRemsOnly.save(outPath+"lgBio_OtherRank"+imgExt)                
			natVegRasters2Sum.append(outPath+"lgBio_OtherRank"+imgExt)
			crs.write("Other Layer:  lgBio_OtherRank"+imgExt)
			crs.write("\n")

		arcpy.AddMessage("-->Calculating Final Vegetation Ranks for Remnants")    
		natVegSum = CellStatistics(natVegRasters2Sum,"SUM","DATA")
		natVegSum.save("xxlg_natVegSum"+imgExt)
		natVegPrjOnly = Times(lgRemsPrjOnly,"xxlg_natVegSum"+imgExt)
		natVegPrjOnly.save("xxlg_natVegPrjOnly"+imgExt)
		FinalRemNatVegSlice = Slice("xxlg_natVegPrjOnly"+imgExt,100,"NATURAL_BREAKS",1)
		FinalRemNatVegSlice.save("xxlg_FinalRemNatVegSlice"+imgExt)
		finalRemNatVegRank = LegalGeo_Routines_Module.scaleUp("xxlg_FinalRemNatVegSlice"+imgExt,100)
		#finalRemNatVegRank = Times("xxlg_FinalRemNatVegSlice"+imgExt,4)
		finalRemNatVegRank.save(outPath+"lgBioAll_RemRank"+imgExt)
		crs.write("Final Remnant Vegetation Layer:  lgBioAll_RemRank"+imgExt)
		crs.write("\n")

		#Regeneration Rank
		arcpy.AddMessage("-->Calculating Final Vegetation Ranks for Converted Lands")    
		natVegRank = LegalGeo_Routines_Module.WeightedDistVeg("xxlg_natVegSum"+imgExt,"BioConv",Rem_ZI_Dist,imgExt)
		natVegRank.save("xxlg_BioConvWD"+imgExt)

		#Raster "xxlg_BioConv_distOnly" created in Weighted distance routine, needed to rank only areas within set distance
		natVeg2Rank = Times(lgConvPrjOnly,"xxlg_BioConvWD"+imgExt)
		natVeg2Rank.save("xxlg_BioConv2Rank"+imgExt)
		finalConvBioRank = Slice("xxlg_BioConv2Rank"+imgExt,100,"NATURAL_BREAKS",1)
		finalConvBioRank.save("xxlg_BioAll_ConvRank"+imgExt)
		finalConvBioRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_BioAll_ConvRank"+imgExt,100)
		finalConvBioRankSave.save(outPath+"lgBioAll_ConvRank"+imgExt)        
		crs.write("Final Converted Lands Vegetation Layer:  lgBioAll_ConvRank"+imgExt)
		crs.write("\n")
		crs.write("Only converted lands within "+str(Rem_ZI_Dist)+ " meters of remnants have been ranked.")
		crs.write("\n")
    except:
        #arcpy.AddMessage("exiting")
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        #arcpy.AddMessage("exiting2")
        pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value)

        arcpy.AddError(pymsg)

        print pymsg    
