
# python parseReplayErrors.py --noauth_local_webserver 

import data2sheets
import gspread
import time
import msgpack
import os

# Now get the google sheet credentials
credentials = data2sheets.authenticate()
gc = gspread.authorize(credentials)

# Open the spreadsheet using the file ID
wks = gc.open_by_key('1gT5kZnOeOaSRi1M-lmRIlTLsG3Xu9MSx-5bMPm3eV-w')
sheetWarn = wks.get_worksheet(0)
sheetErr  = wks.get_worksheet(1)

with open('/net/fermion/mnt/data_drive/SpirentTest/GPSTools/RFPlaybackRegression/OutputResults/all_data.json.bin', 'rb') as f:
  d= msgpack.unpack(f,encoding='utf-8')

index = 0
apiCount = 2

RunNumFile = 'runNum.txt'
if(os.path.isfile(RunNumFile)):
 with open(RunNumFile,'r') as f:
   runNum = int(f.readline())
else:
  runNum = 0

runnumStr = str(runNum)

for curr in d:
  samples = curr['config']['config_filename'].split('Samples/')[1][:-4]
  (date,eventtime) = (curr['date']).split(' ')
  filebase = (curr['file_base'])
  (rxnameStr,runnumStr) = filebase.split('-')

  if(int(runnumStr) <= runNum):
    continue

  try:
    errors    = len(curr['err_log']['errors'])
    warnings  = len(curr['err_log']['warnings'])
    print(date,samples,errors,warnings,rxnameStr,runnumStr)

    # Now output the errors (if there are any)
    for i in range(errors):
      print('Error',curr['err_log']['errors'][i][0],curr['err_log']['errors'][i][1])

      Err = []
      Err.append(date)
      Err.append(eventtime)
      Err.append(curr['err_log']['errors'][i][0])
      Err.append(curr['err_log']['errors'][i][1])
      Err.append(rxnameStr)
      Err.append(runnumStr)
      Err.append(samples)
      print(Err)

      sheetErr.append_row(Err, value_input_option='RAW')
      apiCount += 1
      if(apiCount >= 99):
        print("API sleep to avoid exceeding limit")
        time.sleep(101)
        apiCount = 0

    # Now output the warnings (if there are any)
    for i in range(warnings):
      print('Warning',curr['err_log']['warnings'][i][0],curr['err_log']['warnings'][i][1])

      Warn = []
      Warn.append(date)
      Warn.append(eventtime)
      Warn.append(curr['err_log']['warnings'][i][0])
      Warn.append(curr['err_log']['warnings'][i][1])
      Warn.append(rxnameStr)
      Warn.append(runnumStr)
      Warn.append(samples)
      print(Warn)

      sheetWarn.append_row(Warn, value_input_option='RAW')
      apiCount += 1

      if(apiCount >= 99):
        print("API sleep to avoid exceeding limit")
        time.sleep(101)
        apiCount = 0

  except:
    errors   = 0
    warnings = 0
    print("Expection")
    print(date,samples,errors,warnings,rxnameStr,runnumStr)
    pass
  index += 1

fid = open(RunNumFile,'w')
fid.write("%d" % int(runnumStr))
fid.close()


