#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
import json
import csv
import gdal
import numpy as np
import osgeo.ogr as ogr, osr
sys.path.append("/home/mchc/git/GeoSentinel")
from geosentinel import rasterWkt
from skimage import measure
AREAm = 60*60 #m²
AREAkm = AREAm/1000000#km²
DISTANCE = 60#m

#===============================================================================
def getComponentsMorphology(image_filename, wktlist):
	
	inputImage = gdal.Open(image_filename)
	rows, cols, geotransform = inputImage.RasterYSize, inputImage.RasterXSize, inputImage.GetGeoTransform()
	data = inputImage.GetRasterBand(1).ReadAsArray(0,0,cols,rows)

	areaList = []
	for key, value in wktlist.items():
		print(key)
		dataMask = np.bitwise_and(data, rasterWkt.getPolygonArray(inputImage, value))
		geometry = ogr.CreateGeometryFromWkt(value)

		inSpatialRef = osr.SpatialReference()
		inSpatialRef.ImportFromEPSG(4326)
		outSpatialRef = osr.SpatialReference()
		outSpatialRef.ImportFromEPSG(32514)

		coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)

		geometry.Transform(coordTrans)
		wktArea = geometry.GetArea()

		print(key, wktArea/1000000)


		myDict = dict()
		myDict["clave"] = key
		dataC = dataMask!=0#==i
		myDict["area_tot"]=wktArea/1000000
		myDict["area_verde_tot"] = np.count_nonzero(dataC)

		if myDict["area_verde_tot"]==0.0:
			continue
		myDict["area_verde_tot"]=myDict["area_verde_tot"]*AREAkm
		components_labels = measure.label(dataC)
		myDict["nAreas"] = int( np.max(components_labels))
		properties = measure.regionprops(components_labels)


		myDict["gf1"] = 1 / (myDict["area_verde_tot"]/myDict["nAreas"])
##		myDict["gf2"]
		myDict["gdv"]=myDict["area_verde_tot"]/myDict["area_tot"]
		myDict["vp"]=myDict["area_verde_tot"]
		myDict["tp"]=myDict["area_verde_tot"]/myDict["nAreas"]
		myDict["fp"]=sum([ p["perimeter"]/p["area"] for p in properties])/myDict["nAreas"]
##		print("axis", [ p["minor_axis_length"] for p in properties])
		myDict["alp"]=sum([ 0 if p["minor_axis_length"]==0 else p["major_axis_length"]/p["minor_axis_length"] for p in properties])/myDict["nAreas"]
#		classDict[str(i)]=myDict
		areaList.append(myDict)
		print(myDict)
	with open('morphology.csv', 'w', newline='') as csvfile:
		writer = csv.DictWriter(csvfile, fieldnames=areaList[0].keys())
		writer.writeheader()
		for i in areaList:
			writer.writerow(i)

##	print(classDict)
#	return classDict
#===============================================================================
def main(argv):

	if len(sys.argv) != 3:
		print ("Usage: " + argv[0] + " <reference_image.tif> <wkt_list.csv>")
	else:
		with open(argv[2]) as csvfile:
			reader = csv.DictReader(csvfile)
			areasDic = { row["CVEGEO"]:row["WKT"] for row in reader}
			
			dataDict = getComponentsMorphology(argv[1], areasDic)

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