import requests

from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt
from datetime import date

import time
import progressbar


import numpy as np


#r = requests.get("https://scihub.copernicus.eu/dhus/odata/v1/Products('0d31e8ab-331d-4110-8707-6428102600bf')/$value", auth=('hassanbazzi', '495412789HHH'))
#print(r.text)

user = 'ifayad'
password = 'Geo531988'
dateFrom = '20180301'
dateTo = '20180601'

api = SentinelAPI(user, password, 'https://scihub.copernicus.eu/dhus')
footprint = geojson_to_wkt(read_geojson('C:\\Users\\ibrahim.fayad\\Desktop\\bazbouz\\box.geojson'))
products = api.query(footprint,date=(dateFrom, dateTo),platformname='Sentinel-1',producttype='GRD')
product_status = dict()
PATH = 'C:\\Users\\ibrahim.fayad\\Desktop\\bazbouz\\'

rem = len(products);
pause = False
reachMaxCtr = 0
reachMaxRequest = False
prodName = ""

for key, value in products.items():
    product_status[key] = [0,0]

while(rem > 0):
    
    for key, value in products.items():
        prodName = products[key]['title']
        prodName = prodName[0:4]+prodName[17:32]
        if(reachMaxRequest):
            break
        if(product_status[key][0] == 1 or product_status[key][1] == 1):
            continue
        print("Requesting %s"%(prodName))
        product_info = api.get_product_odata(key)
        if(product_info['Online']):
            print("%s already online, will pass to download"%(prodName))
            product_status[key][0] = 1
            continue
        r = requests.get("https://scihub.copernicus.eu/dhus/odata/v1/Products('%s')/$value" % (key), auth=(user,password))
        print("%s status is %d"%(prodName,r.status_code))
        if(r.status_code == 202):
            product_status[key][0] = 1
            print("Image requested")
        else:
            print("Will attempt request later")
            reachMaxCtr = reachMaxCtr + 1
            if(reachMaxCtr > 2):
                reachMaxRequest = True
            pause = True
    
    for key, value in products.items():
        if(product_status[key][1] == 0):
            product_info = api.get_product_odata(key)
            if(product_info['Online']):
                print("Downloading %s"%(prodName))
                dwnsts = api.download(key,directory_path=PATH)
                if(dwnsts['size'] == dwnsts['downloaded_bytes']):
                    rem = rem-1
                    print("%s Downloaded!! %d/%d remaining"%(prodName,rem,len(products)))
                    product_status[key][1] = 1
                    product_status[key][0] = 1

    if(pause and rem > 0):
        print("Taking pause before rerequesting")
        for i in progressbar.progressbar(range(300)):
            time.sleep(1)
        pause = False
        reachMaxRequest = False
        reachMaxCtr = 0

print("All Downloaded")