#!/usr/bin/python

# Metarace : Cycle Race Abstractions
# Copyright (C) 2012  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/>.

# Convenience program to test printed report templates
#
#
# Usage: testprint template.ini
# or: 	 testprint path/
#
# If a template file is given, all assets will be loaded from the same
# directory. If a path is given, assets will be loaded from that path,
# but the system template will be used.
#
# Output will be a file called output.pdf in the same path as template
# or in the current working directory.
#
import sys
import os

import metarace
from metarace import printing

def main():
    """Run the test print application."""
    cpath = None
    tfile = None

    # expand configpath on cmd line to realpath _before_ doing chdir
    rdir = '.'	# default is cwd with no template
    if len(sys.argv) > 2:
        print('usage: testprint [path/[template.ini]]\n')
        sys.exit(1)
    elif len(sys.argv) == 2:
        rdir = sys.argv[1]
        if os.path.isfile(rdir):
            tfile = os.path.realpath(rdir)
        if not os.path.isdir(rdir):
            rdir = os.path.dirname(rdir)
    cpath = os.path.realpath(rdir)

    metarace.init()
    os.chdir(cpath)
    r = printing.printrep(template=tfile, path=cpath)
    r.set_provisional(True)
    r.set_pagemarks(True)
    r.strings['title'] = 'Example Report'
    r.strings['subtitle'] = 'Subtitle for the example report'
    r.strings['datestr'] = 'Date: The date of the event'
    r.strings['docstr'] = 'Document Ident/Communique'
    r.strings['diststr'] = 'Distance: 123.4km'
    r.strings['commstr'] = 'Chief Commissaire: Gary McName'
    r.strings['orgstr'] = 'Organiser: Event Organiser'

    s = printing.event_index()
    s.heading = 'Index of Events'
    s.subheading = 'Session 1: 10:30am Friday, 21st August 2012'
    #s.colheader = ['Event No.', None, 'Description', None, 'Est. Time', None]
    s.lines.append(['1', '', "U15 Men's Sprint Qualifying", None, '20'])
    s.lines.append(['2', '', "U17 Men's Sprint Qualifying", 'Annot', '16'])
    s.lines.append(['3', '', "U15 Women's Time Trial Final",  'Final', '34'])
    s.lines.append(['', '', "Presentation in event Order", None, None])
    s.lines.append(['4', '', "U17 Men's Scratch Final", 'Final', '15'])
    s.lines.append(['5', '', "U15 Women's Pursuit Qualifying", None, '60'])
    s.lines.append(['', '', "Lunch Break", None, None])
    r.add_section(s)

    s = printing.section()
    s.heading = 'Road Stage Result'
    s.subheading = 'Subheading for a road stage'
    s.colheader = ([None, None, None, 'Cat', 'Time/Gap', 'Bonus', None])
    s.units = 's'
    s.lines.append(['1.', '21', 'First LAST (Team)', 'CATA',
                                                   '1h23:21', '10'])
    s.lines.append(['2.', '5', 'First LAST (Team)', 'CATB',
                                                  '+0', '8'])
    s.lines.append(['3.', '19', 'First LAST (Team)', 'CATC',
                                                  '+1:21', '6'])
    s.lines.append(['4.', '109', 'First LAST (Team)', 'CATD',
                                                   '+1:21', '4'])
    s.lines.append([None, None])
    s.lines.append(['dnf', '29', 'First LAST (Team)', 'CATE', None, None])
    r.add_section(s)

    s = printing.bullet_text()
    s.heading = (u'Li\u2023\u0123st of bulleted paragraphs')
    s.subheading = ('Subheading for the bullet list.')
    #s.bullet = '*'	# alternate bullet
    s.lines.append([None, '23 Rider NAME (Team) behaved poorly during the stage, and hence were penalised. The 1st offence fined $40 and penalised 30 seconds for motorpacing followed by a team fine of $400 for the second offence.\n(CA Annexure 2.3)'])
    s.lines.append(['23a', '24 Rider NAME (Team) fined $400 for failing to attrend official award ceremony.\n(CA Annexure 2.3.2)'])
    r.add_section(s)

    s = printing.preformat_text()
    s.heading = 'Preformatted Text Section'
    s.subheading = 'Subheading for preformatted text block.'
    s.colheader = '012345678901234567890123'
    s.lines = test_receipt.split('\n')
    r.add_section(s)
 
    s = printing.twocol_startlist()
    s.heading = 'Two column mass-start event'
    s.subheading = '10 Laps\tdist/composition\tprogression/medal rule'
    s.timestr = 'Time:'
    s.lines = [
[None,'1','Leigh HOWARD (GEE)','scr',None,None],
[None,'2','Glenn O\'SHEA (SA)','scr',None,None],
[None,'4','Jackson-Leigh RATHBONE (NSW)','15m',None,None],
[None,'5','Franco MARVULLI (SUI)','20m',None,None],
[None,'7','Scott LAW (NSW)','20m',None,None],
[None,'8','Caleb EWAN (NSW)','20m',None,None],
[None,'10','Marcello BARTH (GER)','40m',None,None],
[None,'16','Alexander EDMONDSON (SA)','50m',None,None],
[None,'19','Brent NELSON (BBN)','60m',None,None],
[None,'7','Trent DERECOURT (WA)','80m',None,None],
[None,'35','Peter LOFT (TAS)','90m',None,None],
[None,'40','Owen GILLOTT (QLD)','100m',None,None],
[None,'46','Nathan HART (ACT)','125m',None,None],
[None,'8','Alistair DONOHOE (BBN)','135m',None,None],
[None,'6','Nathan HINKLEY (SA)','180m',None,None],
[None,'64','Jake MCMAHON (TAS)','180m',None,None],
[None,'67','Tyler SPURRELL (BBN)','180m',None,None],
[None,'70','Sam CROME (BGO)','200m',None,None],
[None,'79','Brett ROLLINSON (WGL)','215m',None,None],
[None,'80','James RENDALL (A-W)','220m',None,None] ]
    r.add_section(s)

    s = printing.dual_ittt_startlist()
    s.heading = 'Time Trial/Pursuit Start List'
    s.subheading = '12 Laps\tdist/composition\tprogression/medal rule'
    s.recordstr = 'Australian record: 42.345 Anthea WILSON (VIC), Adelaide 2010'
    s.showheats = True
    #s.set_single()	# overrides showheats
    s.lines = [
[1,'2','Glenn O\'SHEA (SA)','scr',None,None],
[2,'4','Jackson-Leigh RATHBONE (NSW)','15m',None,'5','Franco MARVULLI (SUI)','20m'],
[3,'7','Scott LAW (NSW)','20m',None,'8','Caleb EWAN (NSW)','20m'],
[4,'10','Marcello BARTH (GER)','40m',None,'16','Alexander EDMONDSON (SA)','50m'],
    ]
    r.add_section(s)

    s = printing.rttstartlist()
    s.heading = 'Road Time Trial Startlist'
    s.subheading = 'info\tdist/composition\tprogression/medal rule'
    s.colheader = ['Start',None,'Rider','Cat/Code','chk','xtra']
    s.lines = [
['9:01:00am','1','Leigh HOWARD (GEE)',None,'____',None],
['9:02:00am','2','Glenn O\'SHEA (SA)','U23','____',None],
['9:03:00am','4','Jackson-Leigh RATHBONE (NSW)','U23','____',None],
[None,None,None,None,None,None],
['9:05:00am','5','Franco MARVULLI (SUI)','U23','____','xtra'],
['9:06:00am','7','Scott LAW (NSW)',None,'____','xtra'],
['9:07:00am','8','Caleb EWAN (NSW)',None,'____','xtra'],
['9:08:00am','10','Marcello BARTH (GER)',None,'____',None],
['9:09:00am','16','Alexander EDMONDSON (SA)',None,'____',None],
['9:10:00am','19','Brent NELSON (BBN)',None,'____',None],
['9:11:00am','7','Trent DERECOURT (WA)',None,'____',None],
['9:12:00am','35','Peter LOFT (TAS)',None,'____',None],
['9:13:00am','40','Owen GILLOTT (QLD)',None,'____',None],
['9:14:00am','46','Nathan HART (ACT)',None,'____',None],
['9:15:00am','8','Alistair DONOHOE (BBN)',None,'____',None],
[None,None,None,None,None,None],
['9:17:00am','6','Nathan HINKLEY (SA)','AUS19990123','____',None],
['9:18:00am','64','Jake MCMAHON (TAS)','AUS19800912','____',None],
['9:19:00am','67','Tyler SPURRELL (BBN)','AUS19761201','____',None],
['9:20:00am','70','Sam CROME (BGO)','AUS19930523','____',None],
]
    r.add_section(s)

    s = printing.sprintround()
    s.heading = 'Men\'s Sprint - Round 1 Provisional'
    s.subheading = 'info\tdist/composition\tprogression/medal rule'
    s.lines = [
['1v16:', ['1.','1','Leigh HOWARD (GEE)','scr',None,None],
['2.','2','Glenn O\'SHEA (SA)','scr',None,None], '10.55'],
['2v15:', ['1.','4','Jackson-Leigh RATHBONE (NSW)','15m',None,None],
['2,','5','Franco MARVULLI (SUI)','20m',None,None],'w/o'],
['3v14:', ['1.','7','Scott LAW (NSW)','20m',None,None],
['2.','8','Caleb EWAN (NSW)','20m',None,None],'ntr'],
['4v13:', [None,'10','Marcello BARTH (GER)','40m',None,None],
[None,'16','Alexander EDMONDSON (SA)','50m',None,None]],
['5v12:',[None,'19','Brent NELSON (BBN)','60m',None,None],
[None,'7','Trent DERECOURT (WA)','80m',None,None]],
['6v11:',[None,None,None,None,None,None],
[None,None,None,None,None,None]],
['7v10:',[None,'46','Nathan HART (ACT)','125m',None,None],
[None,'8','Alistair DONOHOE (BBN)','135m',None,None]],
['8v9:',[None,'6','Nathan HINKLEY (SA)','180m',None,None],
[None,'64','Jake MCMAHON (TAS)','180m',None,None]] ]
    r.add_section(s)

    #pad for breakz
    #s = printing.section()
    #s.heading = 'testepuchke'
    #s.subheading = 'testepuchke'
    #for i in range(0,15):
        #s.lines.append([None,'5','Franco MARVULLI (SUI)','20m',None,None])
    #r.add_section(s)

    s = printing.sprintfinal()
    s.heading = 'Men\'s Sprint - Quarter Finals'
    s.subheading = 'info\tdist/composition\tprogression/medal rule'
    s.lines = [
['1v8:', ['1.','1','Leigh HOWARD (GEE)','scr','12.23',None,'11.23',u'\u2713'],
['2.','2','Glenn O\'SHEA (SA)','scr',None,'ntr',None,None]],
['2v7:', ['1.','4','Jackson-Leigh RATHBONE (NSW)','15m',None,None,None,None],
['2,','5','Franco MARVULLI (SUI)','20m','w/o',None,None,u'\u2713']],
['Gold/Silver:', ['1.','7','Scott LAW (NSW)','20m',None,None,None],
['2.','8','Caleb EWAN (NSW)','20m',None,None,None]],
['Bronze:', [None,'10','Marcello BARTH (GER)','40m',None,None,None],
[None,'16','Alexander EDMONDSON (SA)','50m',None,None,None]]]
    r.add_section(s)

    print (u'Default encoding is: ' + repr(sys.getdefaultencoding()))
    ofile = os.path.join(cpath, u'output.pdf')
    with open(ofile, u'wb') as f:
        r.output_pdf(f)
    ofile = os.path.join(cpath, u'output.xls')
    with open(ofile, u'wb') as f:
        r.output_xls(f)
    ofile = os.path.join(cpath, u'output.txt')
    with open(ofile, u'wb') as f:
        r.output_text(f, linkbase=u'/site/output',
                         linktypes=[u'xls', u'pdf', u'txt'])


test_receipt = u"""Ev 1 Time Trial Final   
141 Shirley AMY(CSL)
145 Elizabeth RANDALL(BB
 0023 C0   9h02:26.1675 
 0028 C1   9h02:30.2009 
 0030 C5   9h02:33.8369 
 0032 C4   9h02:36.4104 
 0034 C2   9h02:41.8021 
 0036 C3   9h02:42.0638 
 0038 C1   9h02:42.8094 
 0040 C5   9h02:45.1814 
 0042 C4   9h02:46.6770 
 0044 C3   9h02:51.3850 
145    1:       25.217 
 0046 C2   9h02:52.2306 
141    1:       26.063 
 0048 C1   9h02:53.2240 
 0050 C5   9h02:54.1941 
 0052 C4   9h02:57.1397 
 0054 C2   9h03:00.6829 
 0056 C1   9h03:01.6253 
 0058 C3   9h03:02.0266 
 0060 C5   9h03:04.9639 
 0062 C4   9h03:05.3963 
 0064 C3   9h03:10.2201 
145    2:       18.835 
145   ST:  9h02:26.1675
145  FIN:  9h03:10.2201
145 TIME:       44.052 
 0066 C2   9h03:11.8482 
141    2:       19.617 
141   ST:  9h02:26.1675
141  FIN:  9h03:11.8482
141 TIME:       45.680 """


if __name__ == '__main__':
    main()
