# -*- coding: utf-8 -*-
"""
"""
import argparse
import os
import subprocess 
import sys

import gnssrefl.gps as g
import gnssrefl.rinex2snr as r

def main():
    """

    Creates SNR file from RINEX 3 file that is stored locally
    Requires the gfzrnx executable to be available.
    Does not overwrite existing SNR files. It would be nice if someone would
    add that - plus utilize the libraries for boolean inputs.

    Parameters
    ----------
    rinex3 : str
        name of RINEX3 file
    orb : str
        optional orbit choice.  default is gbm
    snr : int
        snr file choice. default is 66

    """

    parser = argparse.ArgumentParser()
    parser.add_argument("rinex3", help="rinex3 filename", type=str)
    parser.add_argument("-orb", help="orbit choice", default='gbm',type=str)
    parser.add_argument("-dec", help="decimation, in seconds", default=None,type=int)
    parser.add_argument("-snr", help="SNR file ending (default is 66)", default=None,type=int)
    parser.add_argument("-name_fail", help="RINEX 3 files masquerading as RINEX 2.11 files (boolean)", default=None,type=str)
    parser.add_argument("-overwrite", help="whether to overwrite snr file (T or True)", default=None,type=str)
    parser.add_argument("-quiet", help="whether to print gfzrnx log to the screen (default is F)", default=None,type=str)


    args = parser.parse_args()
    if args.snr is None:
        isnr = 66
    else:
        isnr = args.snr

    if args.dec is None:
        dec_rate = 0; 
    else:
        dec_rate = args.dec

    if args.quiet is 'F':
        quiet = False
    else:
        quiet = True

    xdir = os.environ['REFL_CODE']
    r3=args.rinex3
    station4ch = r3[0:4].lower()
    year = int(r3[12:16])
    doy = int(r3[16:19] )

    cyyyy, cyy, cdoy = g.ydoych(year,doy)

    # snr filename
    filename = station4ch + cdoy + '0.' + cyy + '.snr' + str(isnr)
    full_fname = xdir + '/' + cyyyy + '/snr/' + station4ch + '/' + filename

#   snre = g.snr_exist(station4ch,year,doy,str(isnr))
    if os.path.exists(full_fname) or os.path.exists(full_fname + '.gz'):
        snre = True
        # lazy way of doing this
        if (args.overwrite == 'T') or (args.overwrite == 'True'):
            print('Requested SNR file already exists. You requested it be overwritten')
            snre = False
            subprocess.call(['rm','-f',full_fname])
            subprocess.call(['rm','-f',full_fname + '.gz'])
        else:
            print('Requested SNR file already exists.')
            sys.exit()

    #set logs  - this is also used by rinex2snr
    #log, errorlog, exedir,genlog = r.set_rinex2snr_logs(station4ch,year,doy)

    # universal location for the log directory
    logdir, logname = g.define_logdir(station4ch,year,doy)

    logname = logdir + '/' + logname + '.rinex3'


    if (args.name_fail == 'T') or (args.name_fail == 'True'):
        # this is an attempt to help those people impacted by this activity.
        illegal_file = args.rinex3
        print('Someone is using a RINEX 2.11 filename for RINEX 3 data:', illegal_file)

        station = illegal_file[0:4].lower()
        STATION = illegal_file[0:4].upper() + '00ANT'
        cdoy = illegal_file[4:7]
        year = '20' + illegal_file[9:11]
        idoy = int(cdoy) 
        rinex3 = STATION + '_R_' + year + cdoy + '0000_01D_30S_MO.rnx'
        # move the illegal file to its proper name
        subprocess.call(['mv','-f',illegal_file,rinex3])

    else:
        rinex3 = args.rinex3
        station = rinex3[0:4].lower()
        STATION = rinex3[0:4]
        year = rinex3[12:16]
        cdoy = rinex3[16:19] 
        idoy = int(cdoy)

    #print(station, STATION, year, cdoy)
    # all lowercase in my world
    rinex2 = station + cdoy + '0.' + year[2:4] + 'o'
    orbtype = args.orb 
    if orbtype == 'gps':
        orbtype = 'nav'
    elif orbtype == 'gnss':
        orbtype = 'gbm'
    elif orbtype == 'gps+glo':
        orbtype = 'gbm'

    if os.path.isfile(rinex3):
        print('Found version 3 input file \n')
        if (rinex3[-2::] == 'gz'):
            subprocess.call(['gunzip', rinex3])
            rinex3 = rinex3[0:-3]

        idoy = int(cdoy); iyear = int(year)
        # extract 9-char station name from RINEX 3 filename
        station9ch = rinex3[0:9]
        archive = 'unavco'
        rate = 'low'; nol = True
        overwrite = False; srate = 30; mk = False
        strip = False; stream = 'R'; bkg = 'IGS'
        gzip = True; timeout = 0; screenstats = True
        r.run_rinex2snr(station9ch, iyear, idoy, isnr, orbtype, rate,dec_rate,archive,nol,
                overwrite,srate,mk,stream,strip,bkg,screenstats,gzip,timeout,quiet)

    else:
        print('ERROR: your input file does not exist: {0:s} \n'.format(rinex3))
        sys.exit()


if __name__ == "__main__":
    main()
