import os
from glob import glob
from re import sub
from datetime import datetime
import numpy as np
from tools import read_GNSS

os.chdir('/data3/tcliu/gps_pod/python/gnss')

files1 = glob('gnssnrt/*/*_30s.PRE')
files2 = glob('gnssnrt/*/*_GRG30.PRE')
files1.sort()
files2.sort()
dtf1 = [datetime.strptime(sub(r'.*_(\d{7})._.*', r'\1', x), '%Y%j') for x in files1]
dtf2 = [datetime.strptime(sub(r'.*_(\d{7})._.*', r'\1', x), '%Y%j') for x in files2]
dtfs = np.union1d(dtf1, dtf2)[-5:]
for dtf in dtfs:
    dtm = -np.inf
    if dtf in dtf1:
        dtm = os.path.getmtime(files1[dtf1.index(dtf)])
    if dtf in dtf2:
        dtm = max(dtm,os.path.getmtime(files2[dtf2.index(dtf)]))
    gfile = f"gnssOrb/GNSS_{dtf:%Y.%j}_NRT.npz"
    gfile0 = f"gnssOrb/GNSS_{dtf:%Y.%j}_NRT_0.npz"
    if not os.path.exists(gfile) or os.path.getmtime(gfile) < dtm:
        if dtf in dtf1:
            [Gdata, Gdt, Gsats] = read_GNSS(files1[dtf1.index(dtf)])
        if dtf in dtf2:
            [Gdata1, Gdt1, Gsats1] = read_GNSS(files2[dtf2.index(dtf)])
        if dtf in dtf1 and dtf in dtf2:
            if Gdt.shape==Gdt1.shape and np.all(Gdt==Gdt1):
                idx = ~np.isin(Gsats1,Gsats)
                Gsats = np.hstack([Gsats,Gsats1[idx]])
                Gdata = np.hstack([Gdata,Gdata1[:,idx,:]])
            else:
                raise ValueError('Gdt in 30s and GRG30 does not match!')
        elif dtf in dtf2:
            Gdata = Gdata1
            Gdt = Gdt1
            Gsats = Gsats1
        np.savez(gfile0, Gdata=Gdata, Gdt=Gdt, Gsats=Gsats)
        os.rename(gfile0, gfile)

files1 = glob('gnssrt/*/*_COD.PRE')
files2 = glob('gnssrt/*/*_GRG.PRE')
files1.sort()
files2.sort()
dtf1 = [datetime.strptime(sub(r'.*_(\d{7})._.*', r'\1', x), '%Y%j') for x in files1]
dtf2 = [datetime.strptime(sub(r'.*_(\d{7})._.*', r'\1', x), '%Y%j') for x in files2]
dtfs = np.union1d(dtf1, dtf2)[-5:]
for dtf in dtfs:
    dtm = -np.inf
    if dtf in dtf1:
        dtm = os.path.getmtime(files1[dtf1.index(dtf)])
    if dtf in dtf2:
        dtm = max(dtm,os.path.getmtime(files2[dtf2.index(dtf)]))
    gfile = f"gnssOrb/GNSS_{dtf:%Y.%j}_RT.npz"
    gfile0 = f"gnssOrb/GNSS_{dtf:%Y.%j}_RT_0.npz"
    if not os.path.exists(gfile) or os.path.getmtime(gfile) < dtm:
        if dtf in dtf1:
            [Gdata,Gdt,Gsats] = read_GNSS(files1[dtf1.index(dtf)])
        if dtf in dtf2:
            [Gdata1, Gdt1, Gsats1] = read_GNSS(files2[dtf2.index(dtf)])
        if dtf in dtf1 and dtf in dtf2:
            if Gdt.shape==Gdt1.shape and np.all(Gdt==Gdt1):
                idx = ~np.isin(Gsats1,Gsats)
                Gsats = np.hstack([Gsats,Gsats1[idx]])
                Gdata = np.hstack([Gdata,Gdata1[:,idx,:]])
            else:
                ValueError('Gdt in COD and GRG does not match!')
        elif dtf in dtf2:
            Gdata = Gdata1
            Gdt = Gdt1
            Gsats = Gsats1
        np.savez(gfile0, Gdata=Gdata, Gdt=Gdt, Gsats=Gsats)
        os.rename(gfile0, gfile)
