#!/usr/bin/python3
from os.path import expanduser
from datetime import datetime
import eds_defs
import eds_funcs
from eds_funcs import is_valid_date

#if test=True: do nothing, only show what would be done.
test=False

#messages: 0=quiet, 1=errors only, 2: warnings, >2: messages
eds_defs.verbose_level=2
#eds_defs.dry=True

#locations
home=expanduser("~")
eds_defs.path_download=home+'/data/native/zipped'
eds_defs.path_unzipped=home+'/data/native/unzipped'

# Key file
eds_defs.keys_file='eds.key'

#Which product to use
#Direct select
selected_id="EO:EUM:DAT:MSG:HRSEVIRI"
#selected_id="EO:EUM:DAT:MSG:MSG15-RSS"
#selected_id="EO:EUM:DAT:METOP:AVHRRL1"

#Or: read product from eds.prd, line 'nr'
#nr=1
#selected_id = eds_funcs.get_product("eds.prd",nr)
print("Selected: " + selected_id)

#define time period for which to download files
year=2021
start_mon=9
end_mon=9
start_day=19
end_day=20
start_hour=0
end_hour=23
#define minute range to download in 1 stroke (max. 10 downloads at a time!)
minuterange=30

#start and end times; invalid dates will be filtered out
t_start=(start_mon-1)*31*24+(start_day-1)*24+start_hour
t_end  =(  end_mon-1)*31*24+(  end_day-1)*24+end_hour

for t in range(t_start,t_end+1):
  mon=int(t/(31*24)) 
  day=int((t-mon*31*24)/24)
  hour=t-mon*31*24-day*24
  mon=mon+1
  day=day+1

  if (not(is_valid_date(year,mon,day))):
    continue
  for mr in range(0,60-minuterange+1,minuterange):
    start_date = datetime(year,mon, day,hour,mr)
    end_date = datetime(year,mon, day,hour,mr+minuterange-1)
    print("start: " + str(start_date) + " end: " + str(end_date))
    if (test):
      continue
    product_list=eds_funcs.create_list(selected_id,start_date,end_date,0)
    if product_list==[]:
      print("No products available!")
    else:
      eds_funcs.list_datasets(product_list)
      eds_funcs.download_dataset(selected_id,product_list)

