import getTTData
import json
import data2sheets

#
# Script does the following:
#
# * Gets data for 5.50 release from TestTrack
# * Loads a JSON file that refers engineers to the group they report into
# * Parses the open SPRs and determines assignments as a function of group
# * Publishes the data to a google sheet.
#
# The script is called from cron once per day
#
# Copyright Trimble Inc 2020
#

defectList =[ {"TTFilter":"5.55 All SPRs", "GSheet":25},
              {"TTFilter":"5.56 All SPRs", "GSheet":26},
              {"TTFilter":"5.60 - 2022 Q3 - All", "GSheet":27},
              {"TTFilter":"5.61 - 2021 Q2 - All", "GSheet":28},
              {"TTFilter":"5.5X - 2020 - All", "GSheet":29}]

for thisDefect in defectList:
  defects = getTTData.getSPRSummary( "Emerald", thisDefect['TTFilter'])
  sheetId = thisDefect['GSheet']

  unassigned = 0
  missing = 0

  with open('users.json', 'r') as f:
    users = json.load(f)

  # Get a list of teams
  teams = list(users.keys())
  total = [0] * len(teams)
  print(users.keys())

  for i in range(len(defects)):
    status = defects[i]['status']
    phrase= 'assigned to '
    try:
      index = status.index(phrase) + len(phrase)
      assigned = status[index:].split(';')
      for j in range(len(assigned)):
        found = False
        for t in range(len(teams)):
          for k in range(len(users[teams[t]])):
            if(     (users[teams[t]][k]['first'].lower() in assigned[j].lower())
                and (users[teams[t]][k]['last'].lower() in assigned[j].lower()) ):
              total[t] += 1.0 / len(assigned)
              found = True
              break
        if(found == False):
          print("Missing User",assigned[j])
          missing += 1.0 / len(assigned)
    except:
      unassigned += 1

  total_defects = unassigned + missing
  data = []
  data.append(total_defects) # Place holder - update later
  for i in range(len(teams)):
    print(teams[i],total[i])
    total_defects += total[i]
    data.append(total[i])

  # Now we have the total update the first element
  data[0] = total_defects

  print("Unassigned", unassigned)
  print("Missing", missing)
  print("Total", total_defects)
  data.append(unassigned)
  data.append(missing)

  data2sheets.data2row(data,sheetId)

