import datetime as dt
import matplotlib.pyplot as plt
from solo_loader.epd import EPDData
from solo_loader.fluxes import accumulated_spectrum_flux_err
from matplotlib import cm
import numpy as np
import matplotlib.gridspec as gridspec
import datetime as dt
import matplotlib.dates as mdates


def create_axes(fig):
  spec=plt.GridSpec(nrows=7,ncols=1,figure=fig) #,hspace=0.02,wspace=0.02,right=0.88)
  ax1=fig.add_subplot(spec[0,0])
  ax2=fig.add_subplot(spec[1,0])
  #ax2.yaxis.tick_right()
  #ax2.yaxis.set_label_position("right")
  ax3=fig.add_subplot(spec[2,0])
  ax4=fig.add_subplot(spec[3,0])
  ax5=fig.add_subplot(spec[4,0])
  ax6=fig.add_subplot(spec[5,0])
  ax7=fig.add_subplot(spec[6,0])
  axes=[ax1,ax2,ax3,ax4,ax5,ax6,ax7]
  species=["p","p","e","e","he4","he4","p"]
  ranges=["B","C","B","C","B","C","P"]
  direcs=["sun","sun","sun","sun","sun","sun","sun"]
  return axes,species,ranges,direcs

def het_quickplot(sy,sm,sd,ey,em,ed,tres="10min",datatype="nominal",orientation="Portrait",plotname="HET_quickplot_nominal.pdf",show=False):
  sdate,edate=dt.datetime(sy,sm,sd), dt.datetime(ey,em,ed)
  data = EPDData(sdate,edate)
  if orientation=="Portrait":
    fig=plt.figure(figsize=(8.3,11.7))
    plt.subplots_adjust(left=0.12, right=0.98, top=0.97,bottom=0.055, wspace=None, hspace=0.000)
  if orientation=="Landscape":
    fig=plt.figure(figsize=(11.7,8.3))
    plt.subplots_adjust(left=0.07, right=0.93, top=0.957,bottom=0.075, wspace=None, hspace=0.000)
   
  axes,species,ranges,direcs=create_axes(fig)
  for q in range(len(axes)):
    plt.sca(axes[q])
    if datatype=="nominal": hetdata = data.het.science.nominal(species[q], ranges[q])[direcs[q]]
    if datatype=="low_latency": hetdata = data.het.science.low_latency(species[q], ranges[q])[direcs[q]]
    timestamps=hetdata[hetdata.keys()[0]].resample(tres).mean().index.to_numpy()
    flux = hetdata.to_flux().resample(tres).mean()
    flux_scaler=1e5
    plt.plot(timestamps,flux*flux_scaler)
    plt.yscale("log")
    plt.ylabel("Flux: "+"%s - %s - %s"%(species[q],ranges[q],direcs[q]))
    if q==0:  plt.title("most recent HET (%s) data (%s resolution)"%(datatype,tres))

    if q==len(axes)-1:
      myFmt = mdates.DateFormatter('%d %b \n %Y ')  #%H:%M:%S \n #%y %b 
      axes[q].xaxis.set_major_formatter(myFmt)
    else:
      plt.setp(axes[q].get_xticklabels(), visible=False) # do not show tick labels


  #print(dt.datetime.fromtimestamp(timestamps))
  #print(hetdata[hetdata.keys()[0]].index.to_numpy()) #.to_numpy(dtype=object)) #.to_numpy()
  #hetdata.plot()


  if show:  plt.show()
  else:  plt.savefig(plotname)



mytres=input("select timeresolution: i.e. '10min': ")



sy=int(input("Start Year: "))
sd=input("Start Doy ('mm-dd' allowed as well): ")
ey=int(input("End Year: "))
ed=input("Start End ('mm-dd' allowed as well): ")

try:  
    sdoy=int(sd)
    sdate=dt.datetime(sy,1,1)+dt.timedelta(sdoy-1)
    sm=sdate.month
    sd=sdate.day
except:
    sm=int(sd.split("-")[0])
    sd=int(sd.split("-")[1])
try:  
    edoy=int(ed)  
    edate=dt.datetime(ey,1,1)+dt.timedelta(edoy-1)
    em=edate.month
    ed=edate.day
except:
    em=int(ed.split("-")[0])
    ed=int(ed.split("-")[1])

print(sm,sd,em,ed)
het_quickplot(sy,sm,sd,ey,em,ed,tres=mytres,datatype="nominal",orientation="Landscape",plotname="HET_most_recent_NO.PNG",show=True)
#het_quickplot(sy,sm,sd,ey,em,ed,tres=mytres,datatype="low_latency",orientation="Portrait",plotname="HET_most_recent_LL.PNG",show=True)

