#!/usr/bin/python
#
# Pre release draft verion of the program 
# Copyright (C) 2022  John Nicholson
# Verion 24
# Date 9 Febuary 2022
#
# Dependant and using from the following
# Metarace : Cycle Race Abstractions
# Copyright (C) 2016  Nathan Fraser
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ========================================================================
# Special case Events
#
# Madison
#   The rider individual points are allocated to his/her Team points
#   - In the events.csv and njts.csv files will need the Series column to have either of these values
#   - 'fm', 'mm', 'fm5', 'mm5', 'fm7', 'mm7'
#
# Team Sprint and Team Pursuit
#   The column in njts.csv 
#
#
# ========================================================================
import sys
import os
import gobject
import glib
import logging
import metarace
import datetime
import ConfigParser
import json
import xlwt

from decimal import *

from metarace import printing
from metarace import roadmeet
from metarace import strops
from metarace import tod
from metarace import riderdb
from metarace import uiutil
from metarace import ucsv
from metarace import jsonconfig
from metarace import rsync

VERSION = u'1.24'
DESTINATION     = 'auscycling:AUSCYCLING'# This is the value in the metarace/.default/metarace.json file
MIRRORPATH      = '/Track/2027/AJTS2627/Rd1/Day1/'
BASE_INDV       = 32        # The start of all Individual events
BASE_TEAM       = 9         # Start of events in Team file
XLSBASEINDEX    = 5         # 
GC_TEAM_OUTFILE     = u'NJTSteamClassification'
GC_RIDER_OUTFILE    = u'NJTSriderClassification'
GC_XLS_OUTFILE      = u'NJTSextendedClassification'

# read the njts.csv file for extensions of the events.csv file for NJTS
NJTS_CSVFILE = 'njts.csv'
NJTS_EVID   = 0     # the event name usually a number must be the same as the events.csv file
NJTS_PNTS   = 1     # points awarded for each event decending for points for 4 places "6 4 3 2"
NJTS_PART   = 2     # if there are points for participation each rider in the race is awarded this
NJTS_CLASS  = 3     # could be one of three things final, heat, no at the moment only no for no points is used
NJTS_TEAMONLY = 4   # New events that only have Team Points - no individual points 
NJTS_SERIES = 8     # series for madison reuse nr 1 for a team
NJTS_TYPE   = 9     # the race type - this is the same as the Type Handler

NO_EVT_POINTS   = [u'No.', u'no.', u'No', u'no']
YES_TEAMONLY    = [u'Yes.', u'yes.', u'Yes', u'yes']
METARACE_EVT    = 'events.csv'
MADISON_EVT     = [u'tfm', u'tmm', u'tfm5', u'tmm5', u'tfm7', u'tmm7']

# individual riders results for each event in a matrix format
# The previous series status is the file in the root of the event directory
# The will generate this file in the export directory of the event which will be pushed to the WEB
NJTS_INDV_CSVFILE = 'njts_indiv_results.csv'

INDV_BIB        = 0     # race number and series for the rider
INDV_LICE       = 1     # license for rider
INDV_TOTALS     = 2     # total points across all events for this rider
INDV_RANK       = 3     # rank in the category for this rider
INDV_1ST        = 4     # countback 
INDV_2ND        = 5     # countback
INDV_3RD        = 6     # countback
INDV_4TH        = 7     # countback
INDV_5TH        = 8     # countback
INDV_6TH        = 9     # countback
INDV_7TH        = 10     # countback
INDV_8TH        = 11     # countback
INDV_9TH        = 12     # countback
INDV_10TH       = 13     # countback
INDV_11TH       = 14     # countback
INDV_12TH       = 15     # countback
INDV_13TH       = 16     # countback
INDV_14TH       = 17     # countback
INDV_15TH       = 18     # countback
INDV_16TH       = 19     # countback
INDV_17TH       = 20     # countback
INDV_18TH       = 21     # countback
INDV_19TH       = 22     # countback
INDV_20TH       = 23     # countback
INDV_21ST       = 24     # countback
INDV_22ND       = 25     # countback
INDV_23RD       = 26     # countback
INDV_24TH       = 27     # countback
INDV_FIRSTNAME  = 28     # First name of rider
INDV_LASTNAME   = 29     # Surname of rider
INDV_TEAM       = 30    # which team the rider is a member of
INDV_CATS       = 31    # what category the rider is

# Riders for the Round column constants
NJTS_RIDERS_CSVFILE = 'riders.csv'
COL_BIB     = 0
COL_FIRST   = 1
COL_LAST    = 2
COL_CLUB    = 3
COL_CAT     = 4
COL_SERIES  = 5
COL_REFID   = 6
COL_UCICODE = 7
COL_NOTE    = 8

# Multi rider teams eg madison Team Sprint 
MRT_BIB     = 0
MRT_SERIES  = 1
MRT_TEAM    = 2
MRT_RIDERS  = 3
MRT_TEAMONLY = 4

# team results in each event will create a matrix
NJTS_TEAM_CSVFILE = 'njts_team_results.csv'
TEAM_NAME       = 0
TEAM_TOTALS     = 1
TEAM_RANK       = 2
TEAM_FIRSTS     = 3
TEAM_SECONDS    = 4
TEAM_THIRDS     = 5
TEAM_FOUTHS     = 6
TEAM_COUNT      = 7
TEAM_RIDERS     = 8

# Reserved rider numbers.
RESERVED_NOS        = [u'bib', u'no.', u'no', u'No.', u'No', u'all', u'number', u'num']
RESERVED_TEAM       = [u'team', u'Team']
CONFIGFILE          = u'config.json'
LOGFILE             = 'eventTrackSeries.log'
LOGHANDLER_LEVEL    = logging.DEBUG

def datestamp():
    d = datetime.datetime.now()
    return unicode(d.isoformat(' '))

class trackSeries(object):

    def __init__(self):
        self.configpath = ''
        self.reportpath = ''
        self.DOEXPORT = False
        self.ABV_LOCATION = ''

        # Setup logging to a debug file and test mode
        self.log = logging.getLogger()
        self.log.setLevel(logging.DEBUG)
        self.loghandler = None
        self.log.debug(u'opening trackSeries')
        self.loghandler = logging.FileHandler(
                             os.path.join(self.configpath, LOGFILE))
        self.log.addHandler(self.loghandler)
        self.log.info(u'\n=================================\nStarting logging ' + datestamp() + '\n=================================')

        self.riderResults   = []
        self.teamResults    = []
        self.categories     = []
        self.licenseList    = []
        self.madisonTeam    = []
        self.teamMembers    = []


        self.events                 = []        # A list of the current events
        self.eventsTeamOnly         = []        # Team Only Points Events
        self.unfinishedEvents       = ''

        self.currentIndivIndex      = BASE_INDV # This is the column number which is the start column for this race day events
        self.eventsPrevIndvLabels   = []        # This is the previous event labels for this race day eg '1a' or '15'
        self.eventsPrevIndvBlank    = []        # Zero out previous race days event results
        self.eventsIndvCurrentLabel = []        # This is the current event numbers for this race day eg '1a' or '15'
        self.eventsIndvCurrentBlank = []        # Zero out this race days event results

        self.currentTeamIndex       = BASE_TEAM # This is the column number which is the start column for TeamOnly events
        self.eventsPrevTeamLabels   = []        # This is the previous event labels for this race day eg '1a' or '15'
        self.eventsPrevTeamBlank    = []        # Zero out previous race days event results
        self.eventsTeamCurrentLabel = []        # This is the current event numbers for this race day eg '1a' or '15'
        self.eventsTeamCurrentBlank = []        # Zero out this race days event results

        self.reportXLSdata          = {}        # item will be a tab on the xls
        self.reportXLSheader        = {}        # item will be a tab on the xls

# =========================================================================================
# Read the files to load the riders
# =========================================================================================
    def load_riders(self):
        """ 
            Load riders from supplied CSV file.
            Build self.teamResults from riders
        """
        count = 0
        ccount = 0
        DupLicense  = []
        teamName    = []

        if os.path.isfile(NJTS_RIDERS_CSVFILE):
            with open(os.path.join(self.configpath, NJTS_RIDERS_CSVFILE), 'rb') as f:
                cr = ucsv.UnicodeReader(f)
                for row in cr:
                    rRow = [cell.translate(strops.PRINT_UTRANS) for cell in row]
                    madriders = []
                    teamRiders = []
                    if rRow[COL_SERIES] in MADISON_EVT:
                        for x in rRow[COL_NOTE].split():
                            madriders.append(int(x))
                        team = int(rRow[COL_BIB]), rRow[COL_SERIES], rRow[COL_CLUB], madriders
                        self.madisonTeam.append(team)
                    elif rRow[COL_SERIES] in RESERVED_TEAM:
                        for x in rRow[COL_NOTE].split():
                            teamRiders.append(int(x))
                        team = int(rRow[COL_BIB]), rRow[COL_SERIES], rRow[COL_CLUB], teamRiders
                        self.teamMembers.append(team)
                    elif rRow[COL_SERIES] == 'cat':
                        if len(rRow[COL_FIRST].strip()) > 0:
                            self.categories.append([rRow[COL_BIB].strip().upper(), rRow[COL_FIRST].strip()])
                        else:
                            self.categories.append([rRow[COL_BIB].strip().upper(), rRow[COL_BIB].strip().upper()])
                        ccount += 1
                    elif len(rRow) > 0 and rRow[0] not in RESERVED_NOS and rRow[COL_SERIES] not in [u'e',u's',u'p',u'o']:
                        bib = strops.bibser2bibstr(rRow[COL_BIB].strip().lower(), rRow[COL_SERIES].strip().lower())
                        lice = int(rRow[COL_UCICODE].strip().lower())
                        if bib.isalnum() and bib not in RESERVED_NOS:
                            nr = [int(bib), lice, 0, 0, 
                                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   # these are the 24 countback places
                                  rRow[COL_FIRST], rRow[COL_LAST], 
                                  rRow[COL_CLUB], 
                                  rRow[COL_CAT]]
                            self.riderResults.append(nr)
                            count += 1
                            if lice in self.licenseList:
                                DupLicense.append(lice)
                            else:
                                self.licenseList.append(lice)
                        else:
                            self.log.debug(u'Invalid No.: ' + repr(bib))
                        if rRow[COL_CLUB].strip() not in teamName:
                            line = [rRow[COL_CLUB].strip(), 0, 0, 0, 0, 0, 0, 0, []]
                            self.teamResults.append(line)
                            teamName.append(rRow[COL_CLUB].strip())

            if DupLicense != []:
                self.log.debug('*********************************************')
                self.log.debug('Duplicate license number found in riders.csv')
            # work out who is in the teams and count the number of riders
            for row in self.riderResults:
                if row[INDV_TEAM] in teamName:
                    for tRow in self.teamResults:
                        if tRow[TEAM_NAME] == row[INDV_TEAM]:
                            tRow[TEAM_COUNT] += 1
                            tRow[TEAM_RIDERS].append(row[INDV_BIB])
                debugTxt = ''
                if row[INDV_LICE] in DupLicense:
                    for x in self.riderResults[row]:
                        debugTxt = debugTxt + row[x] + ' '
                    self.log.debug(debugTxt)
            if DupLicense != []:
                self.log.debug('*********************************************')
    
            self.log.debug('loaded ' + str(ccount) + ' categories ' + str(count) + ' riders ' + str(len(self.teamResults)) + ' Teams')
            if self.categories == []:
                self.log.debug('WARNING no categories have been loaded check the riders.csv file for cat headers')
        else:
            self.log.debug('File ', NJTS_RIDERS_CSVFILE, ' not found')
            exit(1)

    def readTeamSeriesResults(self):
        """ 
            Read the previous Series Team results spreadsheet
            Update with previous TeamOnly Events and check totals
                self.teamResults
                self.currentTeamIndex
        """
        njtsTeamFile = os.path.join(self.configpath, NJTS_TEAM_CSVFILE)
        teamsFound = []

        if os.path.isfile(njtsTeamFile):
            with open(njtsTeamFile, 'rb') as f:
                cr = ucsv.UnicodeReader(f)
                for x in cr:
                    tRow = [cell.translate(strops.PRINT_UTRANS) for cell in x]
                    if len(tRow) > 0 and tRow[TEAM_NAME].lower() in RESERVED_TEAM:
                        # With the header we build the event mapping
                        self.currentTeamIndex = len(tRow)
                        for previousEvt in range(BASE_TEAM, self.currentTeamIndex):
                            self.eventsPrevTeamLabels.append(tRow[previousEvt])
                            self.eventsPrevTeamBlank.append(0)
                    else:
                        # If a Team makes first appearance in Series
                        if len(tRow) not in [BASE_TEAM, self.currentTeamIndex]:
                            self.log.debug('#319 *** WRONG LINE LENGTH ***')
                        # Check if the Team rode previously but not in the current event 
                        teamsFound.append(tRow[TEAM_NAME])
                        for team in range(len(self.teamResults)):
                            if tRow[TEAM_NAME] == self.teamResults[team][TEAM_NAME]:
                                self.teamResults[team] += self.eventsPrevTeamBlank + self.eventsTeamCurrentBlank

                                # Zero out totals will recalculate later
                                self.teamResults[team][TEAM_TOTALS]    = 0
                                self.teamResults[team][TEAM_RANK]      = 0
                                for place in range(TEAM_FIRSTS, TEAM_FOUTHS):
                                    self.teamResults[team][place] = int(tRow[place])

                                # populate the previous results
                                for previous in range(BASE_TEAM, self.currentTeamIndex):
                                    self.teamResults[team][previous] = int(tRow[previous])

        # Check for a new team for this round
        for tRow in range(len(self.teamResults)):
            if self.teamResults[tRow][TEAM_NAME] not in teamsFound:
                for previous in range(BASE_TEAM, self.currentTeamIndex):
                    self.teamResults[tRow].append(0)

 
    def readIndividualSeriesResults(self):
        """ 
            Read the previous Series Individual results spreadsheet
            Build
                self.riderResults
                self.teamResults
        """
        seriesResultsLicense = []   # a list of license in the previous series results file
        DupLicense = []             # duplicates in this file recorded
        MissMatchFound = False

        njtsSeriesFile = os.path.join(self.configpath, NJTS_INDV_CSVFILE)
        currentTeams = []
        for trow in self.teamResults:
            currentTeams.append(trow[TEAM_NAME])
    
        if os.path.isfile(njtsSeriesFile):
            self.log.info('Adding riders results from previous series events')
            with open(njtsSeriesFile, 'rb') as f:
                cr = ucsv.UnicodeReader(f)
                hasSeriesResults = []
                for x in cr:
                    sRow = [cell.translate(strops.PRINT_UTRANS) for cell in x]
                    if len(sRow) > 0 and sRow[COL_BIB] in RESERVED_NOS:
                        # With the header we build the event mapping
                        self.currentIndivIndex = len(sRow)
                        for previousEvt in range(BASE_INDV, self.currentIndivIndex):
                            self.eventsPrevIndvLabels.append(sRow[previousEvt])
                            self.eventsPrevIndvBlank.append(0)
                    else:
                        if len(sRow) != self.currentIndivIndex:
                            print len(sRow)
                            print self.currentIndivIndex
                            self.log.debug('#372 *** WRONG LINE LENGTH ***')
                        bib = strops.bibser2bibstr(sRow[INDV_BIB].strip().lower(), sRow[COL_SERIES].strip().lower())
                        lice = int(sRow[INDV_LICE].strip().lower())
                        # Test for duplicate license numbers in the Series File NJTS_INDV_CSVFILE
                        if lice in seriesResultsLicense:
                            DupLicense.append(lice)
                        # Test if license number is already in the license numbers in the riders.csv file
                        elif lice not in self.licenseList:
                            self.licenseList.append(lice)
                            seriesResultsLicense.append(lice)
                        else:
                            seriesResultsLicense.append(lice)
                        
                        riderFound = False
                        for mrow in range(len(self.riderResults)):
                            if lice == self.riderResults[mrow][INDV_LICE]:
                                # add the blank previous and current event results
                                self.riderResults[mrow] = self.riderResults[mrow] + self.eventsPrevIndvBlank + self.eventsIndvCurrentBlank
                                hasSeriesResults.append(lice)

                                # update the totals
                                self.riderResults[mrow][INDV_TOTALS]    = int(sRow[INDV_TOTALS])
                                self.riderResults[mrow][INDV_RANK]      = int(sRow[INDV_RANK])
                                for place in range(INDV_1ST, INDV_24TH):
                                    self.riderResults[mrow][place] = int(sRow[place])

                                chkSum = 0
                                # populate the previous results
                                for previous in range(BASE_INDV, self.currentIndivIndex):
                                    self.riderResults[mrow][previous] = sRow[previous]
                                    chkSum += int(sRow[previous])
                                # If the recalcullated sum does not match the total then rewrite the total
                                if chkSum != self.riderResults[mrow][INDV_TOTALS]:
                                    self.log.debug('#405 *** CHANGED TOTALS ***')
                                    self.riderResults[mrow][INDV_TOTALS] = chkSum

                                # Do a Name and Team check
                                if (sRow[INDV_FIRSTNAME].upper()  != self.riderResults[mrow][INDV_FIRSTNAME].upper()) or \
                                   (sRow[INDV_LASTNAME].upper()   != self.riderResults[mrow][INDV_LASTNAME].upper()) or \
                                   (sRow[INDV_TEAM]               != self.riderResults[mrow][INDV_TEAM]) or \
                                   (sRow[INDV_CATS].upper()       != self.riderResults[mrow][INDV_CATS].upper()):
                                    if MissMatchFound:
                                        self.log.debug(str(self.riderResults[mrow][INDV_BIB]) + str(self.riderResults[mrow][INDV_LICE]) + \
                                                       self.riderResults[mrow][INDV_FIRSTNAME] + \
                                                       self.riderResults[mrow][INDV_LASTNAME] + self.riderResults[mrow][INDV_TEAM] + \
                                                       self.riderResults[mrow][INDV_CATS])
                                        self.log.debug(sRow[INDV_BIB], sRow[INDV_LICE], sRow[INDV_FIRSTNAME], sRow[INDV_LASTNAME], sRow[INDV_TEAM], sRow[INDV_CATS])
                                    else:
                                        self.log.debug('*********************************************')
                                        self.log.debug('Difference between riders.csv and ')
                                        self.log.debug('                  ' + NJTS_INDV_CSVFILE)
                                        self.log.debug(str(self.riderResults[mrow][INDV_BIB]) + str(self.riderResults[mrow][INDV_LICE]) + \
                                                       self.riderResults[mrow][INDV_FIRSTNAME] + \
                                                       self.riderResults[mrow][INDV_LASTNAME] + self.riderResults[mrow][INDV_TEAM] + \
                                                       self.riderResults[mrow][INDV_CATS])
                                        self.log.debug(sRow[INDV_BIB] + sRow[INDV_LICE] + sRow[INDV_FIRSTNAME] + sRow[INDV_LASTNAME] + sRow[INDV_TEAM] + sRow[INDV_CATS])
                                        MissMatchFound = True
                                riderFound = True

                        # When the rider has riden earlier events but not this event
                        if not riderFound:
                            chkSum = 0
                            line = [0, lice]
                            for column in range(INDV_TOTALS, INDV_CATS + 1):
                                line.append(sRow[column])
                            line = line + self.eventsPrevIndvBlank + self.eventsIndvCurrentBlank

                            # Populate the previous results
                            for column in range(BASE_INDV, self.currentIndivIndex):
                                line[column] = sRow[column]
                                chkSum += int(sRow[column])
                            # If the recalcullated sum does not match the total then rewrite the total
                            if chkSum != int(line[INDV_TOTALS]):
                                self.log.debug('#445 *** CHANGED TOTALS ***')
                                line[INDV_TOTALS] = chkSum
                            self.riderResults.append(line)
                            hasSeriesResults.append(lice)
                            if sRow[INDV_TEAM] not in currentTeams:
                                print '#450', line[INDV_TEAM]
                                currentTeams.append(line[INDV_TEAM])
                                line = [line[INDV_TEAM], 0, 0, 0, 0, 0, 0, 1, []]
                                self.teamResults.append(line)
                            else:
                                for tr in range(len(self.teamResults)):
                                    if self.teamResults[tr][TEAM_NAME] == line[INDV_TEAM]:
                                        self.teamResults[tr][TEAM_COUNT]  += 1

                # When the rider is new to series
                for rider in range(len(self.riderResults)):
                    if self.riderResults[rider][INDV_LICE] not in hasSeriesResults:
                        self.riderResults[rider] = self.riderResults[rider] + self.eventsPrevIndvBlank + self.eventsIndvCurrentBlank 

                if MissMatchFound:
                    self.log.debug('*********************************************')
                if DupLicense != []:
                    self.log.debug('*********************************************' + DupLicense)
                    self.log.debug('Duplicate license number found')
                    for x in cr:
                        sRow = [cell.translate(strops.PRINT_UTRANS) for cell in x]
                        if len(sRow) > 0 and sRow[COL_BIB] not in RESERVED_NOS:
                            duplice = int(sRow[INDV_LICE].strip().lower())
                        else:
                            duplice = 0
                        if duplice in DupLicense:
                            self.log.debug('Series ' + sRow[INDV_BIB] + sRow[INDV_LICE] + sRow[INDV_FIRSTNAME] + sRow[INDV_LASTNAME] + sRow[INDV_TEAM] + sRow[INDV_CATS])
                            for rrow in self.riderResults:
                                if rrow[INDV_LICE] == duplice:
                                    self.log.debug('Matrix ' + rrow[INDV_BIB] + rrow[INDV_LICE] + rrow[INDV_FIRSTNAME] + \
                                                    rrow[INDV_LASTNAME] + rrow[INDV_TEAM] + rrow[INDV_CATS])
        else:
            self.log.debug('No previous series status file found: ' + NJTS_INDV_CSVFILE)
            # When there are no results as yet
            for rider in range(len(self.riderResults)):
                self.riderResults[rider] = self.riderResults[rider] + self.eventsIndvCurrentBlank 
        

# =========================================================================================
# Read each event and identify placings in the event and allocate points to rider
# =========================================================================================
    def updateMadison(self, event, results, column):
        """
            For the madison applying points to riders 
            self.madisonTeam
        """
        for place in range(len(results)):
            if results[place][1].split(',')[2] != '' and results[place][1].split(',')[0] != 'No':
                for madRiders in self.madisonTeam:
                    if int(results[place][0]) == madRiders[MRT_BIB] and madRiders[MRT_SERIES] == event[NJTS_SERIES]:
                        for rider in self.riderResults:
                            if rider[INDV_BIB] in madRiders[MRT_RIDERS]:
                                # Allocate points to the placed riders
                                if place < len(event[NJTS_PNTS]):
                                    rider[column]       += int(event[NJTS_PNTS][place])
                                    rider[INDV_TOTALS]  += int(event[NJTS_PNTS][place])
                                else:
                                    rider[column]       += int(event[NJTS_PART])
                                    rider[INDV_TOTALS]  += int(event[NJTS_PART])
                                # Record the actual place in the event for count back
                                if place < 24:
                                    rider[INDV_1ST + place] += 1

    def updateTeamEvent(self, event, results, column):
        """ 
            For Team Sprint/Pursuit to applying points to riders Teams
            No Individual points
        """
        
        for place in range(len(results)):
            teamDict = {}
            fullPoints = 0
            if results[place][1].split(',')[2] != '' and results[place][1].split(',')[0] != 'No':
                # Search for team the rider belongs to
                for teamRiders in self.teamMembers:
                    # check we have a match for rider in a team
                    if int(results[place][0]) == teamRiders[MRT_BIB] and teamRiders[MRT_SERIES] == event[NJTS_SERIES]:
                        for rider in self.riderResults:
                            if rider[INDV_BIB] in teamRiders[MRT_RIDERS]:
                                for team in range(len(self.teamResults)):
                                    if self.teamResults[team][TEAM_NAME] == rider[INDV_TEAM]:
                                        if rider[INDV_TEAM] not in teamDict:
                                            teamDict[rider[INDV_TEAM]] = 0
                                        if place < len(event[NJTS_PNTS]):
                                            teamDict[rider[INDV_TEAM]] += int(event[NJTS_PNTS][place])//len(teamRiders[MRT_RIDERS])
                                            if fullPoints == 0:
                                                fullPoints = int(event[NJTS_PNTS][place])
                                        else:
                                            if fullPoints == 0:
                                                fullPoints = int(event[NJTS_PART])
                                            teamDict[rider[INDV_TEAM]] += int(event[NJTS_PART])//len(teamRiders[MRT_RIDERS])
                for teamName in teamDict:
                    for team in range(len(self.teamResults)):
                        if teamName == self.teamResults[team][TEAM_NAME]:
                            if len(teamDict) == 1:
                                self.teamResults[team][TEAM_TOTALS]      += fullPoints
                                self.teamResults[team][INDV_TOTALS] += fullPoints
                                if place < 4:
                                    self.teamResults[team][TEAM_FIRSTS + place] += 1
                            else:
                                self.teamResults[team][TEAM_TOTALS]      += teamDict[teamName]
                                self.teamResults[team][INDV_TOTALS] += teamDict[teamName]

    def openEvent(self, thisEvent, eventName):
        """
            Open the event ini file note some are rawparse and some are json 
        """
        raw_config = []
        config = []
        contests = []
        if os.path.isfile(eventName):
            if thisEvent[NJTS_TYPE] in ['sprint final', 'sprint round']:
                with open(eventName, 'rb') as f:
                    data = json.load(f)
                cr = jsonconfig.config(data)
                if cr.has_section(u'contests'):
                    contests = data[u'contests']
                else:
                    contests = []
                raw_config = []
                config = []
            else:
                raw_config = ConfigParser.RawConfigParser()
                raw_config.read(eventName)
                config = ConfigParser.ConfigParser()
                config.read(eventName)
                contests = []
        else:
            self.log.debug('Event file ' + eventName + ' not found')
        return raw_config, config, contests

    def read_event(self, thisEvent, column, madisonEvent, teamEvent):
        """
            Incriment the index to the first of the event column in the result_matrix
        """
        raceFinished = False
        eventName = os.path.join(self.configpath, 'event_' + thisEvent[NJTS_EVID] + '.ini')
    
        raw_config, config, contests = self.openEvent(thisEvent, eventName)
        if raw_config == []:
            isPoints = False
            isRiders = False
        else:
            isRiders = raw_config.has_section('riders')
            isPoints = raw_config.has_section('points')
    
        # test if an event has results and thus is finished
        if isPoints:
            results = raw_config.items('points')
            if len(results) > 0:
                raceFinished = int(results[0][1].split(',')[1]) > 0 or int(results[0][1].split(',')[2]) > 0
        elif isRiders:
            results = config.items('riders')
            if len(results) > 0:
                if config.has_option('event', 'ctrl_places'):
                    raceFinished = config.get('event', 'ctrl_places') != ''
                else:
                    if results[0][1].split(',')[2] != '':
                        raceFinished = int(results[0][1].split(',')[2]) > 0
        elif contests != []:
            riderA = [0, 0]
            riderB = [0, 0]
            for c in contests:
                if contests[c][1] == '1.':
                    riderA[0] = contests[c][0]
                    riderA[1] += 1
                elif contests[c][3] == '1.':    
                    riderB[0] = contests[c][2]
                    riderB[1] += 1
                if contests[c][1] == '2.':
                    riderA[0] = contests[c][0]
                elif contests[c][3] == '2.':    
                    riderB[0] = contests[c][2]
            raceFinished = riderA[1] == 2 or riderB[1] == 2
            if raceFinished:
                if riderA[1] == 2:
                    results = [(str(riderA[0]), ',,1'), (str(riderB[0]), ',,2')]
                elif riderB[1] == 2:
                    results = [(str(riderB[0]), ',,1'), (str(riderA[0]), ',,2')]
            else:
                results = []

        # Update the matrix with race results
        if raceFinished:
            if madisonEvent:
                column += self.currentIndivIndex
                self.updateMadison(thisEvent, results, column)
            elif teamEvent:
                column += self.currentTeamIndex
                self.updateTeamEvent(thisEvent, results, column)
            else:
                column += self.currentIndivIndex
                for place in range(len(results)):
                    if results[place][1].split(',')[2] != '' and results[place][1].split(',')[0] != 'No':
                        for rider in range(len(self.riderResults)):
                            if self.riderResults[rider][INDV_BIB] == int(results[place][0]):
                                # here we hard code 4 places only in the matrix any more will not be counted
                                if place < len(thisEvent[NJTS_PNTS]):
                                    self.riderResults[rider][column] += int(thisEvent[NJTS_PNTS][place])
                                    self.riderResults[rider][INDV_TOTALS] += int(thisEvent[NJTS_PNTS][place])
                                    # So we have revised to count all places are counted for count back purposes
                                else:
                                    self.riderResults[rider][column] += int(thisEvent[NJTS_PART])
                                    self.riderResults[rider][INDV_TOTALS] += int(thisEvent[NJTS_PART])
                                if place < 24:
                                    self.riderResults[rider][INDV_1ST + place] += 1
        else:
            self.unfinishedEvents += thisEvent[NJTS_EVID] + ' '

# =========================================================================================
# Sort the riders and teams into the placings
# =========================================================================================
    def sort_team(self):
        """ 
            Sort the club results
            Sort by points
        """
        self.teamResults.sort(key=lambda x: x[TEAM_FOUTHS], reverse=True)
        self.teamResults.sort(key=lambda x: x[TEAM_THIRDS], reverse=True)
        self.teamResults.sort(key=lambda x: x[TEAM_SECONDS], reverse=True)
        self.teamResults.sort(key=lambda x: x[TEAM_FIRSTS], reverse=True)
        self.teamResults.sort(key=lambda x: x[TEAM_TOTALS], reverse=True)
    
        place = 0
        equal_place = 0
        previousPnts = 0
        previous = []
    
        for sort_row in range(len(self.teamResults)):
            thispoints = self.teamResults[sort_row][TEAM_TOTALS]
    
            # If we have equal points do a count back
            if thispoints == previousPnts and len(previous) > 0:
                if self.teamResults[sort_row][TEAM_FIRSTS] > previous[TEAM_FIRSTS]:
                    place += 1
                    equal_place = place
                    previousPnts = self.teamResults[sort_row][TEAM_TOTALS]
                    previous = self.teamResults[sort_row]
                elif self.teamResults[sort_row][TEAM_SECONDS] > previous[TEAM_SECONDS]:
                    place += 1
                    equal_place = place
                    previousPnts = self.teamResults[sort_row][TEAM_TOTALS]
                    previous = self.teamResults[sort_row]
                elif self.teamResults[sort_row][TEAM_THIRDS] > previous[TEAM_THIRDS]:
                    place += 1
                    equal_place = place
                    previousPnts = self.teamResults[sort_row][TEAM_TOTALS]
                    previous = self.teamResults[sort_row]
                elif self.teamResults[sort_row][TEAM_FOUTHS] > previous[TEAM_FOUTHS]:
                    place += 1
                    equal_place = place
                    previousPnts = self.teamResults[sort_row][TEAM_TOTALS]
                    previous = self.teamResults[sort_row]
                else:
                    place += 1
            else:
                place += 1
                equal_place = place
                previousPnts = self.teamResults[sort_row][TEAM_TOTALS]
                previous = self.teamResults[sort_row]
            self.teamResults[sort_row][TEAM_RANK] = equal_place

    def sort_cat(self, cat):
        sorted_riders_in_cat = []

        def sort_array(array, *columns):
            for col in columns:
                array.sort(key = lambda x:x[col]) 
               
        # extract the riders in category
        for njts_row in range(len(self.riderResults)):
            if self.riderResults[njts_row][INDV_CATS].upper() == cat:
                sorted_riders_in_cat.append([
                                        self.riderResults[njts_row][INDV_BIB], 
                                        self.riderResults[njts_row][INDV_LICE], 
                                        self.riderResults[njts_row][INDV_TOTALS],
                                        self.riderResults[njts_row][INDV_RANK],
                                        self.riderResults[njts_row][INDV_1ST],
                                        self.riderResults[njts_row][INDV_2ND],
                                        self.riderResults[njts_row][INDV_3RD],
                                        self.riderResults[njts_row][INDV_4TH],
                                        self.riderResults[njts_row][INDV_5TH],
                                        self.riderResults[njts_row][INDV_6TH],
                                        self.riderResults[njts_row][INDV_7TH],
                                        self.riderResults[njts_row][INDV_8TH],
                                        self.riderResults[njts_row][INDV_9TH],
                                        self.riderResults[njts_row][INDV_10TH],
                                        self.riderResults[njts_row][INDV_11TH],
                                        self.riderResults[njts_row][INDV_12TH],
                                        self.riderResults[njts_row][INDV_13TH],
                                        self.riderResults[njts_row][INDV_14TH],
                                        self.riderResults[njts_row][INDV_15TH],
                                        self.riderResults[njts_row][INDV_16TH],
                                        self.riderResults[njts_row][INDV_17TH],
                                        self.riderResults[njts_row][INDV_17TH],
                                        self.riderResults[njts_row][INDV_19TH],
                                        self.riderResults[njts_row][INDV_20TH],
                                        self.riderResults[njts_row][INDV_21ST],
                                        self.riderResults[njts_row][INDV_22ND],
                                        self.riderResults[njts_row][INDV_23RD],
                                        self.riderResults[njts_row][INDV_24TH]
                                       ])
        # Sort by points 
        # The precedences is the number of points then Firsts then Seconds then Thirds and finally Fouths
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_24TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_23RD], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_22ND], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_21ST], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_20TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_19TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_18TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_17TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_16TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_15TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_14TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_13TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_12TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_11TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_10TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_9TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_8TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_7TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_6TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_5TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_4TH], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_3RD], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_2ND], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_1ST], reverse=True)
        sorted_riders_in_cat.sort(key=lambda x: x[INDV_TOTALS], reverse=True)
    
        # Build a tmp sorted riders in cat list
        # also evaluate equal places
        tmp_riders_in_cat = []
        place = 0
        equal_place = 0
        previousPnts = 0
        previous = []
    
        for sort_row in range(len(sorted_riders_in_cat)):
            finished_loop = False
            for njts_row in range(len(self.riderResults)):
                if finished_loop:
                    break
                if self.riderResults[njts_row][INDV_LICE] == sorted_riders_in_cat[sort_row][INDV_LICE]:
                    tmp_njts_row = [self.riderResults[njts_row][INDV_BIB],
                                    self.riderResults[njts_row][INDV_LICE],
                                    self.riderResults[njts_row][INDV_TOTALS], 
                                    self.riderResults[njts_row][INDV_RANK],
                                    self.riderResults[njts_row][INDV_1ST], 
                                    self.riderResults[njts_row][INDV_2ND], 
                                    self.riderResults[njts_row][INDV_3RD], 
                                    self.riderResults[njts_row][INDV_4TH], 
                                    self.riderResults[njts_row][INDV_5TH],
                                    self.riderResults[njts_row][INDV_6TH],
                                    self.riderResults[njts_row][INDV_7TH],
                                    self.riderResults[njts_row][INDV_8TH],
                                    self.riderResults[njts_row][INDV_9TH],
                                    self.riderResults[njts_row][INDV_10TH],
                                    self.riderResults[njts_row][INDV_11TH],
                                    self.riderResults[njts_row][INDV_12TH],
                                    self.riderResults[njts_row][INDV_13TH],
                                    self.riderResults[njts_row][INDV_14TH],
                                    self.riderResults[njts_row][INDV_15TH],
                                    self.riderResults[njts_row][INDV_16TH],
                                    self.riderResults[njts_row][INDV_17TH],
                                    self.riderResults[njts_row][INDV_17TH],
                                    self.riderResults[njts_row][INDV_19TH],
                                    self.riderResults[njts_row][INDV_20TH],
                                    self.riderResults[njts_row][INDV_21ST],
                                    self.riderResults[njts_row][INDV_22ND],
                                    self.riderResults[njts_row][INDV_23RD],
                                    self.riderResults[njts_row][INDV_24TH],
                                    self.riderResults[njts_row][INDV_FIRSTNAME], 
                                    self.riderResults[njts_row][INDV_LASTNAME], 
                                    self.riderResults[njts_row][INDV_TEAM], 
                                    self.riderResults[njts_row][INDV_CATS]
                                   ]
                    if tmp_njts_row[INDV_BIB] == 0:
                        tmp_njts_row[INDV_BIB] = ''
                    thispoints = tmp_njts_row[INDV_TOTALS]
    
                    # Test if there is equal points 
                    # Test 1st, 2nd 3rd and 4th
                    if thispoints == previousPnts and len(previous) > 0:
                        if tmp_njts_row[INDV_1ST] > previous[INDV_1ST]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_2ND] > previous[INDV_2ND]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_3RD] > previous[INDV_3RD]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_4TH] > previous[INDV_4TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_5TH] > previous[INDV_5TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_6TH] > previous[INDV_6TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_7TH] > previous[INDV_7TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_8TH] > previous[INDV_8TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_9TH] > previous[INDV_9TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_10TH] > previous[INDV_10TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_11TH] > previous[INDV_11TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_12TH] > previous[INDV_12TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_13TH] > previous[INDV_13TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_14TH] > previous[INDV_14TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_15TH] > previous[INDV_15TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_16TH] > previous[INDV_16TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_17TH] > previous[INDV_17TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_18TH] > previous[INDV_18TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_19TH] > previous[INDV_19TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_20TH] > previous[INDV_20TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_21ST] > previous[INDV_21ST]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_22ND] > previous[INDV_22ND]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_23RD] > previous[INDV_23RD]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        elif tmp_njts_row[INDV_24TH] > previous[INDV_24TH]:
                            place += 1
                            equal_place = place
                            previousPnts = tmp_njts_row[INDV_TOTALS]
                            previous = tmp_njts_row
                        else:
                            place += 1
                    else:
                        place += 1
                        equal_place = place
                        previousPnts = tmp_njts_row[INDV_TOTALS]
                        previous = tmp_njts_row
    
                    tmp_njts_row[INDV_RANK] = equal_place
                    self.riderResults[njts_row][INDV_RANK] = equal_place
    
                    tmp_riders_in_cat.append(tmp_njts_row)
                    finished_loop = True
    
        return tmp_riders_in_cat

# =========================================================================================
# Create the disk files and reports
# =========================================================================================
    def write_njtsfile(self):
        """ 
            Write the njts' files out to disk
            Individual and Team
            This is the state of the njts
        """
    
        njtsIndividualFile = os.path.join(self.reportpath, 'export', NJTS_INDV_CSVFILE)
        with open(njtsIndividualFile, 'wb') as f:
            cw = ucsv.UnicodeWriter(f)
            cw.writerow([u'No.', u'License', u'Totals', u'Rank', \
                         u'1st', u'2nd', u'3rd', u'4th', u'5th', u'6th', u'7th', u'8th', u'9th', u'10th', \
                         u'11th', u'12th', u'13th', u'14th', u'15th', u'16th', u'17th', u'18th', u'19th', \
                         u'20th', u'21st', u'22nd', u'23rd', u'24th', u'First', u'Last', u'Team', u'Categories', 
                        ] + self.eventsPrevIndvLabels + self.eventsIndvCurrentLabel)
    
            for row in range(len(self.riderResults)):
                line = []
                for item in range(len(self.riderResults[row])):
                    line.append(unicode(self.riderResults[row][item]))
                cw.writerow(line)
    
        njtsTeamFile = os.path.join(self.reportpath, 'export', NJTS_TEAM_CSVFILE)
        for evt in range(len(self.eventsTeamCurrentLabel)):
            self.eventsTeamCurrentLabel[evt] = self.ABV_LOCATION + self.eventsTeamCurrentLabel[evt]
        
        with open(njtsTeamFile, 'wb') as f:
            cw = ucsv.UnicodeWriter(f)
            cw.writerow([u'Team', u'Totals', u'Rank', u'Firsts', u'Seconds', u'Thirds', u'Fourths', u'Count', u'Riders'] + \
                        self.eventsPrevTeamLabels + self.eventsTeamCurrentLabel)
            for row in self.teamResults:
                line = [row[TEAM_NAME], \
                        unicode(row[TEAM_TOTALS]), \
                        unicode(row[TEAM_RANK]), \
                        unicode(row[TEAM_FIRSTS]), \
                        unicode(row[TEAM_SECONDS]), \
                        unicode(row[TEAM_THIRDS]), \
                        unicode(row[TEAM_FOUTHS]), \
                        unicode(row[TEAM_COUNT]), \
                        unicode(row[TEAM_RIDERS])]
                for x in range(BASE_TEAM, len(row)):
                    line.append(unicode(row[x]))
                    
                cw.writerow(line)
    
    def outputEXTxls(self):
        """
            Output xls spreadsheet.
        """
        wb = xlwt.Workbook()
        style1 = xlwt.Style.easyxf('pattern: pattern solid, fore_colour ice_blue; font: bold true, height 560;')
        style2 = xlwt.Style.easyxf('pattern: pattern solid, fore_colour grey25; font: height 186, bold true;')
        style3 = xlwt.Style.easyxf('pattern: pattern solid, fore_colour grey25; font: height 186; alignment: horz center;')
        style4 = xlwt.Style.easyxf('font: height 186; alignment: horz center;')
        style5 = xlwt.Style.easyxf('pattern: pattern solid, fore_colour grey25; font: height 186; alignment: horz left;')
        style6 = xlwt.Style.easyxf('font: height 186; alignment: horz left;')

        for thisCat in self.reportXLSdata:
            if len(self.reportXLSdata) > 0:
                sheet = wb.add_sheet(thisCat)
                sheet.row(0).height = int(3*256)
                sheet.set_panes_frozen(True)
                sheet.set_horz_split_pos(1) 
                sheet.set_vert_split_pos(5)
                sheet.panes_frozen = True
                sheet.horz_split_pos = 2
                sheet.vert_split_pos = 5

                sheet.col(0).width = int(7*256)
                sheet.col(1).width = int(20*256)
                sheet.col(2).width = int(30*256)
                sheet.col(3).width = int(30*256)
                sheet.col(4).width = int(7*256)
                sheet.col(5).width = int(10*256)

                # add top header cat value
                sheet.row(0).write(0, thisCat, style1)
                # add empty cell style to remainer of top header
                for x in range(1, len(self.reportXLSheader[thisCat])):
                    sheet.row(0).write(x, '', style1)

                # Header labels
                for column in range(0, len(self.reportXLSheader[thisCat])):
                    sheet.row(1).write(column, self.reportXLSheader[thisCat][column], style2)

                # Add data 
                for rider in range(0, len(self.reportXLSdata[thisCat])):
                    for column in range(0, len(self.reportXLSdata[thisCat][rider])):
                       # add clean style
                        if (rider % 2) == 0:
                            if column < XLSBASEINDEX:
                                sheet.col(0).width = int(7*256)
                            if column in [1, 2, 3, 4]:
                                sheet.row(rider + 2).write(column, self.reportXLSdata[thisCat][rider][column], style6)
                            else:
                                sheet.row(rider + 2).write(column, self.reportXLSdata[thisCat][rider][column], style4)
                        # add shadded style
                        else:
                            if column < XLSBASEINDEX:
                                sheet.col(0).width = int(7*256)
                            if column in [1, 2, 3, 4]:
                                sheet.row(rider + 2).write(column, self.reportXLSdata[thisCat][rider][column], style5)
                            else:
                                sheet.row(rider + 2).write(column, self.reportXLSdata[thisCat][rider][column], style3)
        destFile = os.path.join(self.reportpath, 'SeriesResults', GC_XLS_OUTFILE + u'.xls')
        self.log.debug('Destination file: ' + destFile)
        wb.save(destFile)

    def results_output(self, webData, outFile, header):
        """
            Sort the results for printing
            read in riders from a particular category 
        """

        tplFile = metarace.default_file(u'pdf_template.json')
        rep = printing.printrep(template=tplFile, path=self.reportpath)
        meet = roadmeet.fakemeet(None, None, self.reportpath)
        meet.loadconfig()
        meet.report_strings(rep)

        # Need to get into the right directory first
        for cat in webData:
            catresults = []
            placeCount = 1
            for aLine in webData[cat]:
                catresults.append(aLine)
                placeCount += 1
            sec = printing.section('thisCat')
            rep.add_section(sec)
            sec.heading = cat
            sec.subheading = ''
            sec.colheader = header
            sec.lines = catresults
        destFile = os.path.join(self.reportpath, outFile)
        lt = [u'pdf', u'xls', u'txt', u'json']
        ld = MIRRORPATH + outFile
        rep.canonical = u'.'.join([ld, u'json'])

        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.xls')
        with open(gc_results_file, u'wb') as f:
            rep.output_xls(f)
        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.pdf')
        with open(gc_results_file, u'wb') as f:
            rep.output_pdf(f)
        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.xls')
        with open(gc_results_file, u'wb') as f:
            rep.output_xls(f)
        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.xls')
        with open(gc_results_file, u'wb') as f:
            rep.output_xls(f)
        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.txt')
        with open(gc_results_file, u'wb') as f:
            rep.output_text(f)
        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.json')
        with open(gc_results_file, u'wb') as f:
            rep.output_json(f)

        gc_results_file = os.path.join(self.reportpath, 'SeriesResults', outFile + u'.html')
        with open(gc_results_file, u'wb') as f:
            rep.output_html(f, ld, linktypes=lt)

# =========================================================================================
# Export the series points files to the WEB location
# =========================================================================================
    def do_export(self, exportpath, EventDir, mirrorpath):
        mirror = rsync.mirror(
                  localpath = os.path.join(exportpath,u''),
                  remotepath = mirrorpath,
                  mirrorcmd = "rsync",
                  arguments = [
                              "--timeout=300",
                              "-avPz",
                              "--rsh=ssh",
                              "{srcdir}",
                              EventDir + "{dstdir}"
                              ]
                  )
        mirror.start()
        mirror.join()

    def buildTeamResults(self):
        for row in self.riderResults:
            for team in range(len(self.teamResults)):
                if row[INDV_TEAM] == self.teamResults[team][TEAM_NAME]:
                    self.teamResults[team][TEAM_TOTALS]     += int(row[INDV_TOTALS])
                    self.teamResults[team][TEAM_FIRSTS]     += int(row[INDV_1ST])
                    self.teamResults[team][TEAM_SECONDS]    += int(row[INDV_2ND])
                    self.teamResults[team][TEAM_THIRDS]     += int(row[INDV_3RD])
                    self.teamResults[team][TEAM_FOUTHS]     += int(row[INDV_4TH])
        for team in range(len(self.teamResults)):
            for column in range(BASE_TEAM, len(self.teamResults[team])):
                self.teamResults[team][TEAM_TOTALS] += int(self.teamResults[team][column])

    def buildWEBriders(self):
        webData = {}
        for row in self.categories:
            riders_in_cat = self.sort_cat(row[0])
            webData[row[1]] = []
            for riderRow in riders_in_cat:
                tmp_row = [
                           unicode(riderRow[INDV_RANK]), 
                           unicode(riderRow[INDV_BIB]), 
                           strops.resname(unicode(riderRow[INDV_FIRSTNAME]), 
                           unicode(riderRow[INDV_LASTNAME]), 
                           unicode(riderRow[INDV_TEAM])), 
                           u'',
                           strops.truncpad(unicode(riderRow[INDV_TOTALS]), 5, 'r')
                           ]
                if riderRow[INDV_TOTALS] > 0:
                    webData[row[1]].append(tmp_row)
        self.results_output(webData, GC_RIDER_OUTFILE, [u'Place', u'Rider#', u'Name', u'', u'Points'])

    def buildWEBteams(self):
        """
            Team results file is created
        """
        webData = {}
        webData['Club/Team Series Points'] = []
        for riderRow in self.teamResults:
            tmp_row = [
                       unicode(riderRow[TEAM_RANK]),
                       u'',
                       unicode(riderRow[TEAM_NAME]), 
                       u'',
                       strops.truncpad(unicode(riderRow[TEAM_TOTALS]), 5, 'r')
                       ]
            if riderRow[TEAM_TOTALS] > 0:
                webData['Club/Team Series Points'].append(tmp_row)
        self.results_output(webData, GC_TEAM_OUTFILE, [u'Place', u'', u'Team', u'', u'Points'])

    def buildXLS(self):
        """
            This builds an xls file with tabs for each categorey
            Each event for the series is recorded as a column
        """
        for evt in range(len(self.eventsIndvCurrentLabel)):
            self.eventsIndvCurrentLabel[evt] = self.ABV_LOCATION + self.eventsIndvCurrentLabel[evt]
        allHeaders   = self.eventsPrevIndvLabels + self.eventsIndvCurrentLabel
        for aCat in self.categories:
            self.reportXLSdata[aCat[1]] = []
            self.reportXLSheader[aCat[1]] = [u'Rank', u'Firstname', u'Surname', u'Club/School', u'Total']

            catRiders   = []
            firstColumn = True
            thisRow     = {}
            for previous in range(BASE_INDV, len(allHeaders) + BASE_INDV):
                haveRace = False
                for row in self.riderResults:
                    if row[INDV_CATS] == aCat[0]:
                        if row[INDV_LICE] not in thisRow:
                            thisRow[row[INDV_LICE]] = [row[INDV_RANK], row[INDV_FIRSTNAME], row[INDV_LASTNAME], row[INDV_TEAM], row[INDV_TOTALS]]
                            catRiders.append(row[INDV_LICE])
                        if int(row[previous]) > 0:
                            haveRace = True
                if haveRace:
                    firstColumn = False
                    self.reportXLSheader[aCat[1]].append(allHeaders[previous - BASE_INDV])
                    for row in self.riderResults:
                        if row[INDV_LICE] in catRiders:
                            thisRow[row[INDV_LICE]].append(int(row[previous]))
            for thisRider in thisRow:
                if thisRider in catRiders:
                    self.reportXLSdata[aCat[1]].append(thisRow[thisRider])
            self.reportXLSdata[aCat[1]].sort(key=lambda x: x[4], reverse=True)
        self.outputEXTxls()

# =========================================================================================
# Read each event and njts.csv which defines the points allocation to placed riders 
# =========================================================================================
    def load_events(self):
        """
        """
        count       = 0
        eventsID    = []
        eventsTeamID = []
        eventsNotID = []
        madisonData = []
        teamEvent   = []    # Team Pursuit or Team Sprint
        teamMember  = []    # Team member

        njtsFile = os.path.join(self.configpath, NJTS_CSVFILE)
        evtFile = os.path.join(self.configpath, METARACE_EVT)

        # First read the NJTS_CSVFILE file to see which event to get results from
        # Get a list eventsList containing EvID (event id text eg event 1)
        # Get a list of events with 5 significant paramaters 
        if os.path.isfile(njtsFile):
            with open(njtsFile, 'rb') as f:
                cr = ucsv.UnicodeReader(f)
                for row in cr:
                    ir = [cell.translate(strops.PRINT_UTRANS) for cell in row]
                    if len(ir) > 0 and ir[NJTS_EVID] != u'EvID':
                        if ir[NJTS_CLASS] in NO_EVT_POINTS:
                            eventsNotID.append(ir[NJTS_EVID])
                        else:
                            nr = [u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']
                            for i in range(len(nr)):
                                if len(ir) > i:
                                    nr[i] = ir[i].strip()
                                    # Split the points into a list
                                    if i == NJTS_PNTS:
                                        nr[i] = nr[i].split()
                                    if i == NJTS_PART:
                                        nr[i] = int(nr[i])
                            nr[NJTS_TEAMONLY] = nr[NJTS_TEAMONLY] in YES_TEAMONLY
                            if nr[NJTS_TEAMONLY]:
                                self.eventsTeamOnly.append(nr)
                                self.eventsTeamCurrentBlank.append(0)
                                self.eventsTeamCurrentLabel.append(nr[NJTS_EVID])  # Event number
                                eventsTeamID.append(nr[NJTS_EVID])
                            else:
                                self.events.append(nr)
                                self.eventsIndvCurrentLabel.append(nr[NJTS_EVID])  # Event number
                                self.eventsIndvCurrentBlank.append(0)
                                eventsID.append(nr[NJTS_EVID])

                            count += 1
                        if nr[NJTS_SERIES] in MADISON_EVT:
                            madisonData.append(ir[NJTS_EVID])
                        elif nr[NJTS_SERIES] in RESERVED_TEAM:
                            teamEvent.append(ir[NJTS_EVID])
                        # Exception if  and is empty then throw an exit
                        if nr[NJTS_TEAMONLY]:
                            if nr[NJTS_SERIES] not in RESERVED_TEAM:
                                txt = ''
                                for x in RESERVED_TEAM:
                                    txt += x + ' '
                                print RESERVED_TEAM, type(RESERVED_TEAM)
                                self.log.debug('------------------------------------------------------------------------------')
                                self.log.debug('*** ERROR WITH EVENT ' + str(ir[NJTS_EVID]) + ' FOR TEAM ONLY EVENTS THE SERIES COLUMN MUST BE IN [' + txt + '] ***') 
                                self.log.debug('------------------------------------------------------------------------------')
                                exit(1)
            # Get all the riders registered for this Round of the NJTS series
            self.load_riders()

            # read previous results from previous events in the series if it exists
            self.readIndividualSeriesResults()

            # read previous team results
            self.readTeamSeriesResults()

            # Work with each individual event update results matrix and team results
            for eRow in range(len(self.events)):
                self.read_event(self.events[eRow], eRow, self.eventsIndvCurrentLabel[eRow] in madisonData, False)
            for eRow in range(len(self.eventsTeamOnly)):
                self.read_event(self.eventsTeamOnly[eRow], eRow, self.eventsTeamCurrentLabel[eRow] in madisonData, True)
            if self.unfinishedEvents != '':
                self.log.debug('------------------------------------------------------------------------------')
                self.log.debug('These events do not have results yet')
                self.log.debug(self.unfinishedEvents)
                self.log.debug('------------------------------------------------------------------------------')
    
            # Get the team totals
            self.buildTeamResults()
            self.buildWEBriders()
            self.sort_team()
            self.buildWEBteams()
            self.buildXLS()

            # write the S/S individual and team files out to disk
            self.write_njtsfile()

            self.log.debug('Loaded ' + unicode(count) + ' events from ' + repr(njtsFile))
        else:
            self.log.debug('File ' + njtsFile + ' not found')

        # To check against the original event file to see if events are misssing
        count_evt = 0
        eventsMID = []
        if os.path.isfile(evtFile):
            with open(evtFile, 'rb') as f:
                cr = ucsv.UnicodeReader(f)
                for x in cr:
                    eRow = [cell.translate(strops.PRINT_UTRANS) for cell in x]
                    if len(eRow) > 0 and eRow[NJTS_EVID] != u'EvID':
                        eventsMID.append(eRow[0])
                        count_evt += 1
        missmatch = False
        eventsFound = eventsID + eventsNotID + eventsTeamID
        for row in range(len(eventsMID)):
            if eventsMID[row] not in eventsFound:
                missmatch = True

        if missmatch:
            self.log.debug( '******************************************************************************')
            self.log.debug( 'This is a simple check of the consistancy between njts.csv and events.csv')
            self.log.debug( 'The following events are missing or have no points allocated in njts.csv')
            self.log.debug( '------------------------------------------------------------------------------')
            for row in range(len(eventsMID)):
                if eventsMID[row] not in eventsFound:
                    self.log.debug( 'Event ' + eventsMID[row] + ' has not been found in njts.csv')
            self.log.debug( '------------------------------------------------------------------------------')
            self.log.debug( 'There will be no points allocated to these events')
            self.log.debug( 'To correct this - add a row in njts.csv file for these events')
            self.log.debug( '******************************************************************************')

        if self.DOEXPORT:
            self.do_export(os.path.join(self.reportpath, 'SeriesResults'), DESTINATION, MIRRORPATH)

def main():
    """
    """

    # expand configpath on cmd line to realpath _before_ doing chdir
    if len(sys.argv) < 5:
        print 'USAGE: report_dir meet_dir DOEXPORT ABV_LOCATION\n'
        print 'report_dir       This directory will contain the classification results\n',\
              'meet_dir         This is event directory which metarace runs from\n',\
              'DOEXPORT         If this is True (case insenative) will push results to WEB\n',\
              'ABV_LOCATION     A descriptive string to identify location in spreadsheets column eg M- for Melbourne\n'
        sys.exit(1)

    configpath = None
    logging.basicConfig(level=logging.INFO)

    trkSeries = trackSeries()
    trkSeries.reportpath = os.path.realpath(sys.argv[1])
    trkSeries.configpath = os.path.realpath(sys.argv[2])

    if (sys.argv[3]).lower() in ['false', '0']:
        trkSeries.DOEXPORT = False
    elif (sys.argv[3]).lower() in ['true', '1']:
        trkSeries.DOEXPORT = True
    else:
        trkSeries.DOEXPORT = False
    trkSeries.ABV_LOCATION = sys.argv[4]

    metarace.init()
    os.chdir(trkSeries.configpath)
    print (u"Junior Track Series Software(" + VERSION + u") Copyright (C) 2022  John Nicholson\n\
This program comes with ABSOLUTELY NO WARRANTY.\n\n")

    # Create if doesn't exist the Report Directory
    temp_path = os.path.join(trkSeries.reportpath, 'SeriesResults')
    if not os.path.exists(temp_path):
        os.mkdir(temp_path)

    trkSeries.load_events()

if __name__ == '__main__':
    main()

