#!/usr/bin/python
# -*- coding: utf-8 -*-
import osgeo.ogr as ogr
import osgeo.osr as osr
import numpy as np
import gdal
import sys
import os
import json
from collections import Counter
#from collections import OrderedDict

########### lee archivo de configuración ################
dirname = os.path.dirname(__file__)
configfile = os.path.join(dirname, '../config/config.json')

with open(configfile, 'r') as f:
    config = json.load(f)


#print(config['PATHS']['PATH_GEOSENTINEL'])

SENTINEL_PATH = config['PATHS']['PATH_GEOSENTINEL']
###########################################################

sys.path.append(SENTINEL_PATH)

from geosentinel import rasterWkt
CLASS_MAP = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:8, 10:8, 11:9}
#-------------------------------------------------------------------------------
def L2ASCLtoDict(filename, wkt, wktsub):
	''' 
	L2ASCLtoDict
	'''
	classMap = lambda x: [ CLASS_MAP[xx] for xx in x ]

	inputImage = gdal.Open(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))


	count1 = Counter([])
	for r in data:
		count1 = count1+ Counter(classMap(r))
	sclDict1 = {str(k):v for k,v in dict(count1).items()}

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

		count2 = Counter([])
		for r in data2:
			count2 = count2 + Counter(classMap(r))
		sclDict2 = {str(k):v for k,v in dict(count2).items()}
	else:
		sclDict2=sclDict1
	return {"areaTotal":sclDict1, "areaNoConservacion":sclDict2}
#-------------------------------------------------------------------------------
def main(argv):
	if len(sys.argv) != 3:
		print("Usage: " + argv[0] + "<JSON SCL> <JSON Cfg>")
	else:
		jsonFile=open(argv[2]).read()
		cfg = json.loads(jsonFile)
		dataDict = L2ASCLtoDict(argv[1], cfg['wkt'], cfg["wkt2"])
		print(json.dumps(dataDict, sort_keys=True))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
	main(sys.argv)
