#!/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/geoint/GeoSentinel")
from geosentinel import rasterWkt
from skimage import measure
AREAm = 60*60 #m²
AREAkm = AREAm/1000000#km²
DISTANCE = 60#m

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

	data1 = np.bitwise_and(data, rasterWkt.getPolygonArray(inputImage, wkt))
	if wktsub!="":
		data2 = np.bitwise_and(data1, np.invert(rasterWkt.getPolygonArray(inputImage, wktsub)))
	else:
		data2 = data1

	geometry = ogr.CreateGeometryFromWkt(wkt)
	inSpatialRef = osr.SpatialReference()
	inSpatialRef.ImportFromEPSG(4326)
	outSpatialRef = osr.SpatialReference()
	outSpatialRef.ImportFromEPSG(32514)

	coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)
	geometry.Transform(coordTrans)
	wktArea = geometry.GetArea()
	classDict={}
	for i in range(12):

		myDict = dict()		
		dataC = data2==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"]

		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
#		print(myDict)
#	print(classDict)
	return classDict
#===============================================================================
def main(argv):

	if len(sys.argv) != 3:
		print (argv[0] + " <image.tif> <cfg.json>")
	else:
		with open(argv[2]) as jsonFile:
			cfg = json.load(jsonFile)
			dataDict = getComponentsMorphology(argv[1], cfg["wkt"], cfg["wkt2"])
			print(json.dumps(dataDict, sort_keys=True))

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