import json
import RXTools as rx # Trimble receiver communication tools (in GPSTools/pythonTools)
import argparse
import xmltodict

# Script to get the MAC address and hostname from mutliple receivers
# Uses the same format JSON file as some other scripts, e.g.,
#
# GPSTools/pythonTools/rxSummary.py
# GPSTools/pythonTools/clearErrLog.py
# GPSTools/DHSTest/flashRX.py -s stress_flash.json
# GPSTools/DHSTest/configRX.py
# GPSTools/DHSTest/DHSApp.py
#
# The script finds the MAC and hostname and adds/replaces them in the
# JSON (creating a new file). This may be useful when we move receivers
# to the new building!
#

if __name__ == "__main__":
  newFormat = False
  ######################################################################
  # Parse arguments
  parser = argparse.ArgumentParser(description='Get Receiver hostname/MAC')
  parser.add_argument('filename', nargs=2,help='input.json output.json')
  parser.add_argument('-s','--stations', help='Filename of the station JSON e.g. --stations global.json')
  args = parser.parse_args()
  ######################################################################

  filename = args.filename
  if args.filename:
    inputFile, outputFile = args.filename
  else:
    print('Need input/output filenames')
    sys.exit()

  # Load the list of stations
  if(inputFile):
    with open(inputFile,'r') as f: 
      jsonData = json.load(f)

    stations = []
    gotStations = False
    # New JSON format
    for i in range(len(jsonData)):
      if('RX' in jsonData[i]):
        stations = jsonData[i]['RX']
        newFormat = True
        gotStations = True
    
    # Old format
    if(gotStations == False):
      stations = jsonData
  else:
    print('require a station JSON file')
    sys.exit(1)
 


  for thisStation in stations:
      url = '/xml/dynamic/merge.xml?&sysData='
      
      try:
        resp = rx.SendHttpGet( thisStation.get("addr"), 
                               url,
                               thisStation.get("user"), 
                               thisStation.get("pw"),
                               verbose=False,
                               timeout=5)
        data = xmltodict.parse(resp)
        MAC = data['data']['sysData']['mac']
        hostname = data['data']['sysData']['DNSName']
        RXName = data['data']['sysData']['RXName']
        sn = data['data']['sysData']['serial']
        ownerStr = data['data']['sysData']['ownerString1']
        # For some reason the hostname ends with a "."
        if(hostname.endswith('.')):
          hostname = hostname[:-1]

        print(thisStation.get("addr"),MAC,hostname)
        # Pust the MAC address into the config data
        thisStation['MAC'] = MAC
        thisStation['Host'] = hostname
        thisStation['RXName'] = RXName
        thisStation['sn'] = sn
        thisStation['ownerStr'] = ownerStr
      except:
        print(thisStation.get("addr"),"Problem")


  if(newFormat == True):
    for i in range(len(jsonData)):
      if('RX' in jsonData[i]):
        jsonData[i]['RX'] = stations
    json_formatted_str = json.dumps(jsonData, indent=2)
  else:
    json_formatted_str = json.dumps(stations, indent=2)

  with open(outputFile,"w") as fid:
    fid.write(json_formatted_str)

