# 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

#MAY NEED to check output for conv in case there are no values for conv


def legalRank(LR_Dist,LR_ZI_Dist,PPA_Dist,PPA_ZI_Dist,PA_Dist,PA_ZI_Dist,inPath,outPath,imgExt,crs): 
    # DETERMINE PROJECTION UNITS...

	lgRems = inPath+"lg_REMs"+imgExt
	lgRemOnes = inPath +"lg_REM_Ones"+imgExt
	lrOnes = inPath+"lgLegal_LR_Ones"+imgExt
	LRs = inPath+"lgLegal_LRs"+imgExt
	ppaOnes = inPath+"lgLegal_PPA_Ones"+imgExt
	paOnes = inPath+"lgLegal_PA_ones"+imgExt
	PAs = inPath+"lgLegal_PAs"+imgExt
	CPAs = inPath+"lgLegal_CPAs"+imgExt
	LegalOther = inPath+"lgLegal_other"+imgExt

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


	desc = arcpy.Describe(lgRems)    # describe object
	cellSize = desc.MeanCellHeight      # cell size
	spatRef = desc.SpatialReference
	units = spatRef.LinearUnitName      # projection units
	if "Foot" in units:
		outUnit = "Feet"
	elif "Meter" in units:
		outUnit = "Meters"
	else:
		arcpy.AddError("lg_REM_Ones coordinate system has been changed.")

	del desc

	LegalRemSum = []
	LegalConvSum =[]

	#need to use in final ranking 
	legalBufRems = []
	legalBufConvs = []

	legalDataUsed= []
	legalRemLRPA_Rank=[]
	#Note used slice with 10 categories here due to small number of remnants possibly being 
	if arcpy.Exists("xxlg_remSizeInCells"+imgExt):
		remSizeRaster = "xxlg_remSizeInCells"+imgExt
	else:
		remSizeRaster = Lookup(lgRems,"COUNT")
		remSizeRaster.save("xxlg_remSizeInCells"+imgExt)

	if arcpy.Exists(lrOnes):
		arcpy.AddMessage("-->Runnning Legal Reserves analysis")
		legalDataUsed.append(" Legal Reserves ")
		
		
				
		lrArea = LegalGeo_Routines_Module.areaCalc(LRs,"LRs",imgExt)
		lrArea.save("xxlg_lrArea"+imgExt)

		lrWD = LegalGeo_Routines_Module.WeightedDistLegal("xxlg_lrArea"+imgExt,"LRs",LR_ZI_Dist,imgExt)
		lrWD.save("xxlg_lrWD"+imgExt)

		whereClause = "Value <= "+str(LR_Dist)
		lrRank =  Con("xxlg_LRs_dist"+imgExt,90,"",whereClause)
		lrRank.save("xxlg_lrBufRank"+imgExt)
		


		#Remnant Ranking
		RankLRRem = LegalGeo_Routines_Module.rankVals("xxlg_lrWD"+imgExt,"LRs",lgRemsPrjOnly,imgExt)
		RankLRRem.save("xxlg_RankLRRem"+imgExt)
		lrBufRemsOnly = Times(lgRemsPrjOnly,"xxlg_lrBufRank"+imgExt)
		lrBufRemsOnly.save("xxlg_lrBufRemsOnly"+imgExt)
		legalBufRems.append("xxlg_lrBufRemsOnly"+imgExt)
		lrMaxList = ["xxlg_lrBufRemsOnly"+imgExt,"xxlg_RankLRRem"+imgExt]
		lrMaxVal = CellStatistics(lrMaxList,"MAXIMUM","DATA")
		lrMaxVal.save(outPath+"lgLegal_LRsRank"+imgExt)
		LegalRemSum.append(outPath+"lgLegal_LRsRank"+imgExt)
		crs.write("Proximity to Legal Reserves (remnants) = lgLegal_LRsRank"+imgExt+"\n")            

		#Conv Ranking 
		lrBufConvsOnly = Times(lgConvPrjOnly,"xxlg_lrBufRank"+imgExt)
		lrBufConvsOnly.save("xxlg_lrBufConvsOnly"+imgExt)
		legalBufConvs.append("xxlg_lrBufConvsOnly"+imgExt)

		


		FinalRankLRConvSU = LegalGeo_Routines_Module.rankVals("xxlg_lrWD"+imgExt,"LRsConv",lgConvPrjOnly,imgExt)
		FinalRankLRConvSU.save("xxlg_FinalRankLRConvSU"+imgExt)
		FinalRankLRConvSave = CellStatistics(["xxlg_FinalRankLRConvSU"+imgExt,"xxlg_lrBufConvsOnly"+imgExt],"MAXIMUM","DATA")
		FinalRankLRConvSave.save(outPath+"lgLegal_ConvLRsRank"+imgExt)
		LegalConvSum.append(outPath+"lgLegal_ConvLRsRank"+imgExt)
		crs.write("Proximity to Legal Reserves (converted areas): lgLegal_ConvLRsRank"+imgExt+"\n")
		crs.write("Only lands within "+str(LR_ZI_Dist)+ " meters of any legal reserves were used in ranking. \n")
		crs.write("All lands within "+str(LR_Dist)+" meters of any legal reserves were given at minimum ranking value of 90.\n\n")   
		
		
	if arcpy.Exists(ppaOnes):
		arcpy.AddMessage("-->Running Permanently Protected Area analysis...")
		legalDataUsed.append(" Permanently Protected Areas")
		

		   
		ppaSD = LegalGeo_Routines_Module.SimpleDistLegal(ppaOnes,"PPAs",PPA_ZI_Dist,imgExt)
		ppaSD.save("xxlg_ppaSD"+imgExt)            


		whereClause = "Value <= "+str(PPA_Dist)
		appRank =  Con("xxlg_PPAs_dist"+imgExt,90,"",whereClause)
		appRank.save("xxlg_PPABufRank"+imgExt)
		appBufRemsOnly = Times(lgRemsPrjOnly,"xxlg_PPABufRank"+imgExt)
		appBufRemsOnly.save("xxlg_PPABufRemsRank"+imgExt)  
		legalBufRems.append("xxlg_PPABufRemsRank"+imgExt)
		ppaBufConvsOnly = Times(lgConvPrjOnly,"xxlg_PPABufRank"+imgExt)
		ppaBufConvsOnly.save("xxlg_PPABufConvsOnly"+imgExt)
		legalBufConvs.append("xxlg_PPABufConvsOnly"+imgExt)     

		#Rem Ranking
		RankLRRem = LegalGeo_Routines_Module.rankVals("xxlg_ppaSD"+imgExt,"PPAs",lgRemsPrjOnly,imgExt)
		RankLRRem.save("xxlg_RankPPAsRem"+imgExt)
		appMaxList = ["xxlg_RankPPAsRem"+imgExt,"xxlg_PPABufRemsRank"+imgExt]
		appMaxVal = CellStatistics(appMaxList,"MAXIMUM","DATA")
		appMaxVal.save(outPath+"lgLegal_PPAsRank"+imgExt)
		LegalRemSum.append(outPath+"lgLegal_PPAsRank"+imgExt)
		crs.write("Proximity to Permanently Protected Areas (remnants): lgLegal_PPAsRank"+imgExt+"\n")
		
		#Regen ranking

		FinalRankPPaConvSaveSU = LegalGeo_Routines_Module.rankVals("xxlg_ppaSD"+imgExt,"PPAsConv",lgConvPrjOnly,imgExt)
		FinalRankPPaConvSaveSU.save("ppaSU"+imgExt)
		FinalRankPPaConvSave = CellStatistics(["ppaSU"+imgExt,"xxlg_PPABufConvsOnly"+imgExt],"MAXIMUM","DATA")
		FinalRankPPaConvSave.save(outPath+"lgLegal_ConvPPAsRank"+imgExt)
		LegalConvSum.append(outPath+"lgLegal_ConvPPAsRank"+imgExt)            
		crs.write("Proximity to Permanently Protected Areas (converted areas): lgLegal_ConvPPAsRank"+imgExt+"\n")
		crs.write("Only lands within "+str(PPA_ZI_Dist)+ " meters of any permanentaly protected areas were used in ranking. \n")
		crs.write("All lands within "+str(PPA_Dist)+" meters of any permanentaly protected areas were given a minimum ranking value of 90.\n\n")   

		
	if arcpy.Exists(paOnes):
		arcpy.AddMessage("-->Running Protected Area analysis...")
		legalDataUsed.append(" Protected Areas")

		paArea = LegalGeo_Routines_Module.areaCalc(PAs,"PAs",imgExt)
		paArea.save("xxlg_paArea"+imgExt)
		
		paWD = LegalGeo_Routines_Module.WeightedDistLegal("xxlg_paArea"+imgExt,"PAs",PA_ZI_Dist,imgExt)
		paWD.save("xxlg_paWD"+imgExt)
		
		
		


		whereClause = "Value <= "+str(PA_Dist)
		paRank =  Con("xxlg_PAs_dist"+imgExt,100,"",whereClause)
		paRank.save("xxlg_paBufRank"+imgExt)
		paBufRemsOnly = Times(lgRemsPrjOnly,"xxlg_paBufRank"+imgExt)
		paBufRemsOnly.save("xxlg_paBufRemsOnly"+imgExt)
		legalBufRems.append("xxlg_paBufRemsOnly"+imgExt)
		paBufConvsOnly = Times(lgConvPrjOnly,"xxlg_paBufRank"+imgExt)
		paBufConvsOnly.save("xxlg_paBufConvsOnly"+imgExt)
		legalBufConvs.append("xxlg_paBufConvsOnly"+imgExt)
	 
		#Remnant Ranking
		RankLRRem = LegalGeo_Routines_Module.rankVals("xxlg_paWD"+imgExt,"PAs",lgRemsPrjOnly,imgExt)
		RankLRRem.save("xxlg_RankPARem"+imgExt)            
		
		paMaxList = ["xxlg_paBufRemsOnly"+imgExt,"xxlg_RankPARem"+imgExt]
		paMaxVal = CellStatistics(paMaxList,"MAXIMUM","DATA")
		paMaxVal.save(outPath+"lgLegal_PAsRank"+imgExt)
		LegalRemSum.append(outPath+"lgLegal_PAsRank"+imgExt)
		crs.write("Proximity to Protected Areas (remnants) = lgLegal_PAsRank"+imgExt+"\n")
		

		FinalRankPAConvSU = LegalGeo_Routines_Module.rankVals("xxlg_paWD"+imgExt,"PAsConv",lgConvPrjOnly,imgExt)
		FinalRankPAConvSU.save("paSU"+imgExt)
		FinalRankPAConvSave = CellStatistics(["paSU"+imgExt,"xxlg_paBufConvsOnly"+imgExt],"MAXIMUM","DATA")

		FinalRankPAConvSave.save(outPath+"lgLegal_ConvPAsRank"+imgExt)
		LegalConvSum.append(outPath+"lgLegal_ConvPAsRank"+imgExt)
		crs.write("Proximity to Protected Areas (converted areas): lgLegal_ConvPAsRank"+imgExt+"\n")
		crs.write("Only lands within "+str(PA_ZI_Dist)+ " meters of any protected areas were used in ranking. \n")
		crs.write("All lands within "+str(PA_Dist)+" meters of any protected areas were given at minimum ranking value of 100.\n\n") 



	if arcpy.Exists(CPAs):
		arcpy.AddMessage("-->Running Conservation Priority analysis...")
		legalDataUsed.append(" Priority Conservation Areas")

		cpaSum = ZonalStatistics(lgRems,"Value",CPAs,"SUM","DATA")
		cpaSum.save("cpaSum"+imgExt)            
		cpaRank = LegalGeo_Routines_Module.rankVals("cpaSum"+imgExt,"CPAs",lgRemsPrjOnly,imgExt)

		cpaRank.save("xcpaRank"+imgExt)
		CPAsOnes = Con(CPAs,1,"","Value > 0")
		CPAsOnes.save("cpaOnes"+imgExt)
		cpaRankSave = Times("xcpaRank"+imgExt,"cpaOnes"+imgExt)

		cpaRankSave.save(outPath+"lgLegal_CPAsRank"+imgExt)
		LegalRemSum.append(outPath+"lgLegal_CPAsRank"+imgExt)
		crs.write("Conservation Priority Areas: lgLegal_CPAsRank"+imgExt+"\n")



	if arcpy.Exists(LegalOther):
		arcpy.AddMessage("-->Running Ecological or Other Zoning analysis...")
		legalDataUsed.append(" Ecological Zoning")
		otherSum = ZonalStatistics(lgRems,"Value",LegalOther,"SUM","DATA")
		otherSum.save("otherSum"+imgExt)            
		otherRank = LegalGeo_Routines_Module.rankVals("otherSum"+imgExt,"Others",lgRemsPrjOnly,imgExt)
		otherRank.save("xLegalOtherRank"+imgExt)
		OtherOnes = Con(LegalOther,1,"","Value>0")
		OtherOnes.save("legalOtherOnes"+imgExt)
		otherRankSave = Times("legalOtherOnes"+imgExt,"xLegalOtherRank"+imgExt)
		otherRankSave.save(outPath+"lgLegal_OtherRank"+imgExt)            
		LegalRemSum.append(outPath+"lgLegal_OtherRank"+imgExt)
		crs.write("Other Zoning: lgLegal_OtherRank"+imgExt+"\n")


	#Remnants Ranking
	legalRemRankSum = CellStatistics(LegalRemSum,"SUM","DATA")
	legalRemRankSum.save("xxlg_legalRemRankSum"+imgExt)
	RemLegalRankSum = LegalGeo_Routines_Module.rankVals("xxlg_legalRemRankSum"+imgExt,"LegalRem",lgRemsPrjOnly,imgExt)

	#new 2016
	if len(legalBufRems) > 0:
	#new Sunday
		RemLegalRankSum.save("legalRankSum"+imgExt)
		legalBufRems.append("legalRankSum"+imgExt)
		RemLegalRank = CellStatistics(legalBufRems,"MAXIMUM","DATA")
	#new Sunday  

		RemLegalRank.save(outPath+"lgLegalAll_RemRank"+imgExt) 
	else:
		RemLegalRankSum.save(outPath+"lgLegalAll_RemRank"+imgExt) 
	crs.write("Final Remnant Legal Layer:  lgLegalAll_RemRank"+imgExt)
	crs.write("\n")


	#Converted lands Ranking
	#new 2016
	#new 2016
	if len(LegalConvSum) > 0:
		sumConvLegal = CellStatistics(LegalConvSum,"SUM","DATA")
		sumConvLegal.save("xxlg_sumConvLegal"+imgExt)
		ConvLegalRankSum = LegalGeo_Routines_Module.rankVals("xxlg_sumConvLegal"+imgExt,"LegalConv",lgConvPrjOnly,imgExt)  
	#new Sunday
		ConvLegalRankSum.save("legalRankConvSum"+imgExt)
		legalBufConvs.append("legalRankConvSum"+imgExt)
		ConvLegalRank = CellStatistics(legalBufConvs,"MAXIMUM","DATA")
	#new Sunday 

		ConvLegalRank.save(outPath+"lgLegalAll_ConvRank"+imgExt)
		crs.write("Final Converted Legal Layer:  lgLegalAll_ConvRank"+imgExt)
		crs.write("\n")
	else:
		crs.write("Final Converted Legal Layer:  not produced due to know PPAs, LRs, or PAs present.")
		crs.write("\n")			