#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
import csv
import json
from datetime import date, datetime


sys.path.append("/home/mchc/git/GeoSentinel")
from geosentinel import findProducts
csv.field_size_limit(sys.maxsize)
#===============================================================================
def greenIndexAnalisis(csvfile, cfg):

	today = date.today()
	startDate = datetime.strptime(cfg["startDate"], '%Y%m%d')

	regionList = {}	
	with open(csvfile) as csvfile:
		reader = csv.DictReader(csvfile)
		for row in reader:
			regionList[row["CVE_ENT"]] = row["WKT"]

	os.chdir(cfg["projectDir"])
	if not os.path.isdir(cfg["productLevel"]):
		os.mkdir(cfg["productLevel"])

	if not os.path.isdir("out"):
		os.mkdir("out")

	os.chdir("out")	
	for y in range(today.year, startDate.year-1, -1):
		year = str(y)
		if not os.path.isdir(year):
			os.mkdir(year)
		os.chdir(year)
		for key, value in regionList.items():
			settings = cfg
			settings["wkt"]=value
			settings["endDate"]= date.today().strftime("%Y%m%d")
			findProducts.findSentinelProducts(settings)


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

	if len(argv) != 3:
		print ("Usage: " + argv[0] + "<regionList.csv> <settings.json>")
	else:
		with open(argv[2]) as json_file:
			cfg = json.load(json_file)
			greenIndexAnalisis(argv[1], cfg)


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