#!/usr/bin/env python
from datetime import datetime, timedelta
import re, string
import numpy as np
import os, glob
from satellite_info import env_paths, sat_ant_info

__authors__ = ["Ming Chen"]
__license__ = "Public Domain"
__maintainer__ = "Ming Chen"
__email__ = "ming.chen@noaa.gov"
__date__  = "July 1, 2023"

'''
#####################################################################
# 
# utility.py
#
# Purpose:
# This Python script provides a collection of utility functions for
# supporting the data processing workflow.
##
# History:  
#       Created by: Ming Chen 2023/07/01
#                   ming.chen@noaa.gov
# 
# Usage: import utility
#
#
#####################################################################

'''
def str2date(datestr):
    if len(datestr) == 8:
       mydate = datetime.strptime(datestr,'%Y%m%d')
    elif len(datestr) == 7:
       mydate = datetime.strptime(datestr,'%Y%j')
    else:
       print("Error str2date input, usage: yyyymndd or yyyyddd ")
       return None 
    return (mydate)

def leofile_time_range(filename, **kwargs):      
    verbose = kwargs.get('verbose', False)
    # ftype = os.path.splitext(filename)[1]
    if not os.path.isfile(filename):
       err = "Error: file not exis {} ... ".format(filename)
       print(err)
       return(False)
    if(verbose): print(filename)
       
    btime = r'(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\.\d+)'
    htime = r'(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+\.\d+)\s+(\w+)\s+(\.+)'
    pbt=re.compile(btime)

    fp = open(filename, 'r' )
    start_time = None ; end_time = None 
    while True:
      line = fp.readline()
      if len(line) == 0: break
      if line.find("first") != -1 or line.find("FIRST") != -1:
         if(verbose): print(line)
         ts = pbt.search(line.strip())
         dstr1="{:04d}{:02d}{:02d}".format(int(ts[1]),int(ts[2]),int(ts[3]))
         dstr2="T{:02d}:{:02d}:{:06.3f}".format(int(ts[4]),int(ts[5]),float(ts[6]))
         start_time = dstr1+dstr2
      if line.find("last") != -1 or line.find("LAST") != -1:
         if(verbose): print(line)
         ts = pbt.search(line.strip())
         dstr1="{:04d}{:02d}{:02d}".format(int(ts[1]),int(ts[2]),int(ts[3]))
         dstr2="T{:02d}:{:02d}:{:06.3f}".format(int(ts[4]),int(ts[5]),float(ts[6]))
         end_time = dstr1+dstr2
         break
    return (start_time, end_time)



def leofile_time_range_from_data(filepath):
    # RINEX 2 epoch line regex
    epoch_pattern = re.compile(
        r'^\s*(\d{2})\s+(\d{1,2})\s+(\d{1,2})\s+'
        r'(\d{1,2})\s+(\d{1,2})\s+([\d\.]+)'
    )

    first_epoch = None
    last_epoch = None
    in_header = True

    with open(filepath, "r") as f:
        for line in f:
            if in_header:
                if "END OF HEADER" in line:
                    in_header = False
                continue

            match = epoch_pattern.match(line)
            if match:
                yy, mm, dd, hh, mi, ss = match.groups()

                # convert 2-digit year ? 4-digit
                yy = int(yy)
                year = 2000 + yy if yy < 80 else 1900 + yy

                ts = (year, int(mm), int(dd), int(hh), int(mi), float(ss))

                dstr1="{:04d}{:02d}{:02d}".format(ts[0],ts[1],ts[2])
                dstr2="T{:02d}:{:02d}:{:06.3f}".format(ts[3],ts[4],ts[5])
                if first_epoch is None:
                    first_epoch = dstr1+dstr2

                last_epoch = dstr1+dstr2

    return first_epoch, last_epoch

def list_leoatt_files(mission, satidx, datestr, leopath=None,  **kwargs): 

    satinfo = sat_ant_info(mission, satidx)
    if satinfo == None: return   
    satsvn =  satinfo['satsvn'] ; satname = satinfo['satname'] 
    paths = env_paths()
    if leopath == None:
       leopath =  os.environ['D']
    if leopath == None:
       print("no leopath specified ... ")
       return None 
    sdate = str2date(datestr)
    year = sdate.strftime('%Y') ; jday = sdate.strftime('%j')
    yy = int(year)-2000 ; yy = "{:02d}".format(yy) 

    fnames=satname+yy+jday+'[A-Z]'+'.ATT'
    leodir = os.path.join(leopath, 'LEO', 'ATTIT')
    #print(leodir)
    filelist = glob.glob(leodir+'/'+fnames, recursive=False)  
    filelist.sort()
    return (filelist)

def list_leornx_files(mission, satidx, antidx, datestr, leopath=None,  **kwargs): 

    satinfo = sat_ant_info(mission, satidx, antidx)
    if satinfo == None: return   
    satsvn =  satinfo['satsvn'] ; satname = satinfo['satname'] 
    antenna = satinfo['antsvn'] 
    if antenna == None: 
       print("error in antidx {}".format(antidx))
       return None

    paths = env_paths()
    if leopath == None:
       leopath =  os.environ['D']
    if leopath == None:
       print("no leopath specified ... ")
       return None 
    sdate = str2date(datestr)
    year = sdate.strftime('%Y') ; jday = sdate.strftime('%j')
    yy = int(year)-2000 ; yy = "{:02d}".format(yy) 
    fnames=satname+jday+'[A-Z]'+'.'+yy+'O'+'_A'+antenna

    leodir = os.path.join(leopath, 'LEO', 'RINEX')
    #print(leodir)
    filelist = glob.glob(leodir+'/'+fnames, recursive=False)  
    filelist.sort()
    return (filelist)
