
import RXTools
import os
import random
import argparse
import datetime
import time
import xmltodict

# To run from a fresh Anaconda 3.X python install:
# conda install -c conda-forge xmltodict

# Default settings
user = 'admin'
password = 'password'

#
# The script will randomly download converted files, setting the 
# desired format based on the following lists.
#
# see coreBuild/ecos/web/web_file.c
#
# Get a list of the conversion arguments passed
# via the URL
conv = [ {'type':'Zipped-RNX-MIX', 'output':'zip'},
         {'type':'Zipped-RNX-COMP', 'output':'zip'},
         {'type':'Zipped-RNX', 'output':'zip'},
         {'type':'RNX-COMP', 'output':'zip'},
         {'type':'Zipped-RNX-MIX', 'output':'zip'},
         {'type':'Zipped-RNX-COMP-MIX', 'output':'zip'},
         # No compression
         {'type':'RNX-GPS', 'output':'txt'},
         {'type':'RNX-GLN', 'output':'txt'},
         {'type':'RNX-GAL', 'output':'txt'},
         {'type':'RNX-QZS', 'output':'txt'},
         {'type':'RNX-MIX', 'output':'txt'},
         {'type':'RNX', 'output':'txt'} ]

# The RINEX version is a modifier on the URL, get a list
# of the supported types
RINEXVer = [ 'Ver=2.11',
             'Ver=2.12',
             'Ver=3.00',
             'Ver=3.02',
             'Ver=3.03',
             'Ver=3.04']

parser = argparse.ArgumentParser(description="Stresses RINEX on download conversion",
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument("IPAddr", help="IP Address of the receiver")
parser.add_argument("--user", help="Username")
parser.add_argument("--password", help="Password")
args = parser.parse_args()

IPAddr = args.IPAddr
if(args.user is not None):
  user = args.user

if(args.password is not None):
  password = args.password

path = '/Internal'

while(True):
  ret = RXTools.GetDirectory(IPAddr,user,password,path)
  # Get a direcotory listing
  filename = []
  for line in ret.splitlines():
    if("file" in line):
      data = line.split()
      filename.append(data[1][5:])

  if(len(filename) == 0):
    # No files - wait a little while and try again.
    time.sleep(60) 
    continue

  # Get a random index into the list of files
  i = random.randint(0,len(filename) - 1)
  # Make sure the index is a T02 or T04 file
  if( filename[i][-3:] == 'T02' or filename[i][-3:] == 'T04'):
    ISOStr = datetime.datetime.now().isoformat()
    print(ISOStr,filename[i])

    try:
      convType = random.randint(0,len(conv) - 1)
      rinType  = random.randint(0,len(RINEXVer) - 1)
      urlSegment = filename[i] + '?format=' + conv[convType]['type'] + '&' + RINEXVer[rinType]
      outputFile = filename[i] + '.RINEX.' + conv[convType]['output']
      print(urlSegment)
      RXTools.getFileHTTP(IPAddr,user,password,
                          '.','/Internal',
                          outputFile,
                          urlSegment) # note - getFileHTTP() will add more to the URL

      filesize = os.path.getsize(outputFile)
      print("Download size = " + str(filesize))
      os.remove(outputFile)
    except:
      # This script is a first hack and has not been carefully validated. Some
      # of the combinations of conversion type "conv[]" and the RINEX version "RINEXVer" may
      # not be valid. That may be one cause of the script throwing this exception. If that is 
      # case, please adjust the script and commit to CVS.
      print('Error')

    try:
      # The script uses a secure connection (HTTPS) so that any memory malloced by this transaction
      # shows in the HTTPS tasks, the HTTPD tasks should now have any active mallocs (at least not 
      # from this scripts, there could be other active connections).
      ret = RXTools.SendHttpGet(IPAddr,'/xml/dynamic/dyn_mem_info.xml',user,password,secure=True)
      data = xmltodict.parse(ret)
      for i in range(len(data['data']['task'])):
        if('HTTP' in data['data']['task'][i]['name']):
          print("%s %s %s %s %s %s" % 
                (data['data']['task'][i]['name'],
                 data['data']['task'][i]['usage'],
                 data['data']['task'][i]['maxUsage'],
                 data['data']['task'][i]['taskActiveMallocs'],
                 data['data']['task'][i]['taskMallocCount'],
                 data['data']['task'][i]['taskFreeCount']))
    except:
      print("Problem reading dynamic memory")




