#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
import json
import csv
#===============================================================================
def getMinMax(clase):

	polylist = []
	morphList = []
	for item in os.listdir("."):
		if os.path.isdir(item):
			print(item)
			with open(os.getcwd()+"/"+item+"/scl_data.json") as json_file:
				dataSCL = json.load(json_file)

			with open(os.getcwd()+"/"+item+"/scl_morph.json") as json_file:
				dataMorph = json.load(json_file)
				
			with open(os.getcwd()+"/"+item+"/findProducts.json") as json_file:
				dataWKT = json.load(json_file)
			wkt = dataWKT["wkt"]
			

			polyDict = {"clave": item, "wkt":wkt}

			cDict = {k:v["areaTotal"][clase] for k, v in dataSCL.items() }
			maxkey = max(cDict, key=cDict.get )
			maxval = dataSCL[maxkey]["areaTotal"][clase]
			polyDict["areaTotal"] = maxval
			
			
			cDict = {k:v["areaNoConservacion"][clase] for k, v in dataSCL.items() if clase in v["areaNoConservacion"]}

			if len(cDict) >0 and clase in dataSCL[maxkey]["areaNoConservacion"]:
				maxkey = max(cDict, key=cDict.get )
				maxval = dataSCL[maxkey]["areaNoConservacion"][clase]

			else:
				maxval=0
			polyDict["areaNoConservacion"] = maxval
			polylist.append(polyDict)


			tmpDict = dataMorph[maxkey][clase]
			tmpDict["wkt"] = wkt
			tmpDict["clave"]=item
			morphList.append(dataMorph[maxkey][clase])
	
	with open('minmax_'+clase+'.csv', 'w') as outfile:
		writer = csv.DictWriter(outfile, fieldnames=polylist[0].keys())
		writer.writeheader()
		for item in polylist:
			writer.writerow(item)

	with open('morphology_'+clase+'.csv', 'w') as outfile:
		writer = csv.DictWriter(outfile, fieldnames=morphList[0].keys())
		writer.writeheader()
		for item in morphList:
			writer.writerow(item)

#===============================================================================
def main(argv):

	if len(sys.argv) != 2:
		print ("Usage text")
	else:
		getMinMax(argv[1])


if __name__ == "__main__":
	main(sys.argv)
