import sys
import datetime
import time

import pymap3d as pm

from ionotec import stations
from ionotec import gnss
from ionotec import tec
from ionotec import graph


from os import listdir, makedirs
from os.path import isfile, join, exists
from pathlib import Path

import georinex as gr
import pandas as pd
import shutil

import matplotlib.pyplot as plt

#tec.st.create_output("output")

#sys.exit()

#shutil.rmtree('output')
data="C:\\Users\\User\\Documents\\TEC\\data\\"



#print (f_obs)

dir_plot = "output/Figs/P1P2/"
if not exists(dir_plot): makedirs(dir_plot) 

#obs_station = "antc"
#nav_station = "brdc"
year = 2020

list_doy = [i for i in range(274,293)]
list_doy = [i for i in range(345,351)]
date = datetime.date(year, 1, 1) + datetime.timedelta(days=list_doy[0] - 1)
month = date.month

f_nav = []
for doy in list_doy:
    folder = Path(data+str(year)+"\\"+str(doy)+"\\")
    f_nav = f_nav+[f for f in folder.glob('*g') if f.is_file()]
    f_nav = f_nav+[f for f in folder.glob('*n') if f.is_file()]
    
    #nav_n_brdc = data+str(year)+"\\"+str(doy)+"\\"+"brdc"+str(doy)+"0.22n"
    #nav_g_brdc = data+str(year)+"\\"+str(doy)+"\\"+"brdc"+str(doy)+"0.22g"
    #nav_g_sant = data+str(year)+"\\"+str(doy)+"\\"+'SANT00CHL_R_'+str(year)+str(doy)+'0000_01D_RN.rnx' 
    #if exists(nav_n_brdc): f_nav.append(nav_n_brdc)
    #if exists(nav_g_brdc): f_nav.append(nav_g_brdc)
    #if exists(nav_g_sant): f_nav.append(nav_g_sant)

#f_bias=data+str(year)+"\\"+str(list_doy[int(len(list_doy)/2)])+"\\"+"P1P2"+str(year-2000)+str(month)+".DCB"
#print (f_nav)
#sys.exit()
    
f_bias=data+str(year)+"\\"+str(345)+"\\"+"CAS0MGXRAP_20203450000_01D_01D_DCB.BSX"
#print (getBias("G01",f_bias))
#print (getBias("R01",f_bias))

#sys.exit()

list_stations = []

for doy in list_doy:
    folder = Path(data+str(year)+"\\"+str(doy)+"\\")
    list_stations = list_stations+[f.name[:4] for f in folder.glob('*o') if f.is_file()]
list_stations = sorted(list(set(list_stations)))

print ("list_stations")
print (len(list_stations))
sys.exit()
#print ("f_nav")
#print (f_nav)
#print ("f_obs")
#print (f_obs)

for station in list_stations[2:]:
    if exists("output/TEC/2020/"+station+".feather"): continue
    print (station)
    f_obs = []
    for doy in list_doy:
        obs = data+str(year)+"\\"+str(doy)+"\\"+station+str(doy)+"0."+str(year-2000)+"o"
        #print (obs)
        if exists(obs): f_obs.append(obs)

    print (f_obs)
    t1 = time.time()
    station_tec = tec.tec(f_obs,f_nav,f_bias)
    station_tec.compute_vtec()
    t2 = time.time()
    print ("time to process ", t2-t1)
    #stations.resume_station(data,year=2020,doy=349,out_csv="output/stations.csv")

    #print (station_tec.df_obs)
   
    #sys.exit()
    #graph.plot_station(station_tec.df_obs,dir_plot+obs_station,mozaic=False)
    #graph.plot_station(station_tec.df_obs,dir_plot+station,mozaic=True)
    if exists("output/TEC/2020/"+station+".feather"):
        df_obs = pd.read_feather("output/TEC/2020/"+station+".feather")
        df_obs["time"] = pd.to_datetime(df_obs["time"])
        df_obs.set_index("time",inplace=True)
        graph.plot_station(df_obs,dir_plot+station,mozaic=False)
    #print (df_obs)

sys.exit()


#time_list =  self.df_obs.index

#print ("GLONASS")
#gps = gnss.gnss([data+"2020\\349\\brdc3490.20g"])
#print ("GPS")
#gps = gnss.gnss([data+"2020\\349\\alma3491.20n"])
#print ("GALILEO")
#gps = gnss.gnss([data+"2020\\349\\areg3490.20l"])


#gps = gnss.gnss(f_nav)

#d_in, d_out = datetime.datetime(2020,12,14,0,0,0,0),datetime.datetime(2020,12,14,23,59,0,0)
#gps.load_sats(d_in,d_out)

#df_pos = gps.df_pos.copy()

#df_pos["lat"],df_pos["lon"],df_pos["alt"] = pm.ecef2geodetic(df_pos["X"],df_pos["Y"],df_pos["Z"])


#print (df_pos)
#n_sat = 24
#g = "R"
#list_r_sat = [str(i+1) for i in range(n_sat)]
#for s in range(10):
#    list_r_sat[s] = "0"+list_r_sat[s]

#for s in range(n_sat):
#    list_r_sat[s] = g+list_r_sat[s]




'''
import matplotlib.pyplot as plt

df_posR = df_pos[df_pos["sv"].isin(list_r_sat)]

fig,ax = plt.subplots(4,8,figsize=(20,17))

for i,sat in enumerate(list_r_sat):
    x,y = int(i/8),i%8
    df_sat = df_posR[df_posR["sv"]==sat]
    df_sat_15 = df_sat[df_sat.index<datetime.datetime(2020,12,14,0,15,0,0)]
    df_sat_45 = df_sat[df_sat.index>datetime.datetime(2020,12,14,23,45,0,0)]
    ax[x,y].plot(df_sat["lon"],df_sat["lat"],'.',markersize=1)
    ax[x,y].plot(df_sat_15["lon"],df_sat_15["lat"],'*',markersize=1)
    ax[x,y].plot(df_sat_45["lon"],df_sat_45["lat"],'*',markersize=1)
    
    ax[x,y].set_title(sat)

plt.savefig(g+"_trajectory_satellites.png",bbox_inches="tight")
'''


#t_tot = 0
#t_full = 0
#tf = time.time()


#self.df_obs = gps.getElevation(self.df_obs,self.coord)
#self.df_obs = gps.getPiercingPoint(self.df_obs,self.coord,self.h)

#f_obs = ["C:\\Users\\User\\Documents\\TEC\\data\\igs\\ALME00ESP_R_20252970300_01H_30S_MO.crx"]
#f_nav = ["C:\\Users\\User\\Documents\\TEC\\data\\igs\\ALBA00ESP_R_20252970300_01H_MN.rnx"]

#station_tec = tec.tec(f_obs,f_nav,f_bias)
#station_tec.compute_vtec()

#from ionotec import graph

#graph.plot_station(station_tec.df_obs,"output/antc",mozaic=False)
