import time
import datetime
from dateutil import parser as ps
import lxml

import numpy as np
from lxml import etree, objectify
from lxml.etree import XMLSyntaxError
import urllib2

namespace = 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'

def lap_begin(f,datetimestring,totalmeters,avghr,maxhr,avgspm,totalseconds):
    f.write('        <Lap StartTime="{s}">\n'.format(s=datetimestring))
    f.write('          <TotalTimeSeconds>{s}</TotalTimeSeconds>\n'.format(s=totalseconds))
    f.write('          <DistanceMeters>{s}</DistanceMeters>\n'.format(s=totalmeters))
    f.write('          <Calories>1</Calories>\n')
    f.write('          <AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">\n')
    f.write('            <Value>{s}</Value>\n'.format(s=avghr))
    f.write('          </AverageHeartRateBpm>\n')

    f.write('          <MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">\n')
    f.write('            <Value>{s}</Value>\n'.format(s=maxhr))
    f.write('          </MaximumHeartRateBpm>\n')
    f.write('          <Intensity>Active</Intensity>\n')
    f.write('          <Cadence>{s}</Cadence>\n'.format(s=avgspm))
    f.write('          <TriggerMethod>Manual</TriggerMethod>\n')
    f.write('          <Track>\n')

    
def lap_end(f):
    f.write('          </Track>\n')
    f.write('          <Notes>rowingdata export</Notes>\n')
    f.write('        </Lap>\n')


def write_tcx(tcxFile,df,row_date="2016-01-01"):
    f = open(tcxFile,'w')
    
    totalseconds = int(df[' ElapsedTime (sec)'].max())
    totalmeters = int(df[' Horizontal (meters)'].max())
    avghr = int(df[' HRCur (bpm)'].mean())
    maxhr = int(df[' HRCur (bpm)'].max())
    avgspm = int(df[' Cadence (stokes/min)'].mean())

    seconds = df['TimeStamp (sec)'].values
    distancemeters = df[' Horizontal (meters)'].values
    heartrate = df[' HRCur (bpm)'].values
    cadence = df[' Cadence (stokes/min)'].values

    nr_rows = len(seconds)

    try:
	lat = df[' latitude'].values
    except KeyError:
	lat = np.zeros(nr_rows)

    try:
	long = df[' longitude'].values
    except KeyError:
	long = np.zeros(nr_rows)

    s = "2000-01-01"
    tt = ps.parse(s)
    timezero = time.mktime(tt.timetuple())
    if seconds[0]<timezero:
	print "Taking Row_Date ",row_date
	dateobj = ps.parse(row_date)
	unixtimes = seconds+time.mktime(dateobj.timetuple())


    
    f.write('<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n')
    f.write('<TrainingCenterDatabase')
    f.write('  xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"\n')
    f.write('  xmlns:ax="http://www.garmin.com/xmlschemas/ActivityExtension/v2"\n')
    f.write('  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n')
    f.write('xsi:schemaLocation="http://www.garmin.com/xmlschemas/ActivityExtension/v2 http://www.garmin.com/xmlschemas/ActivityExtensionv2.xsd http://www.garmin.com/xmlschemas/FatCalories/v1 http://www.garmin.com/xmlschemas/fatcalorieextensionv1.xsd http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">\n')
    f.write('  <Activities>\n')
    f.write('    <Activity Sport="Other">\n')

    datetimestring = row_date

    f.write('      <Id>{s}</Id>\n'.format(s=datetimestring))

    lap_begin(f,datetimestring,totalmeters,avghr,maxhr,avgspm,totalseconds)

    for i in range(nr_rows):
	    
	f.write('          <Trackpoint>\n')
	s = datetime.datetime.fromtimestamp(unixtimes[i]).isoformat()
	f.write('            <Time>{s}</Time>\n'.format(s=s))
	if (lat[i] != 0) & (long[i] != 0 ):
	    f.write('            <Position>\n')
	    f.write('              <LatitudeDegrees>{lat}</LatitudeDegrees>\n'.format(
		lat=lat[i]
		))
	    f.write('              <LongitudeDegrees>{long}</LongitudeDegrees>\n'.format(
		long=long[i]
		))
	    f.write('            </Position>\n')
	f.write('            <DistanceMeters>{d}</DistanceMeters>\n'.format(
	    d=distancemeters[i]
	    ))
	f.write('            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">\n')
	f.write('              <Value>{h}</Value>\n'.format(h=heartrate[i]))
	f.write('            </HeartRateBpm>\n')
	f.write('            <Cadence>{c}</Cadence>\n'.format(c=cadence[i]))
	f.write('          </Trackpoint>\n')



    f.write('          </Track>\n')
    f.write('        </Lap>\n')
    f.write('      <Notes></Notes>\n')
    f.write('    </Activity>\n')
    f.write('  </Activities>\n')
    f.write('  <Author xsi:type="Application_t">\n')
    f.write('    <Name>CrewNerd</Name>\n')
    f.write('    <Build>\n')
    f.write('      <Version>\n')
    f.write('        <VersionMajor>0</VersionMajor>\n')
    f.write('        <VersionMinor>75</VersionMinor>\n')
    f.write('      </Version>\n')
    f.write('      <Type>Release</Type>\n')
    f.write('    </Build>\n')
    f.write('    <LangID>EN</LangID>\n')
    f.write('    <PartNumber>000-00000-00</PartNumber>\n')
    f.write('  </Author>\n')
    f.write('</TrainingCenterDatabase>\n')

    f.close()

    file = open(tcxFile,'r')
    
    some_xml_string = file.read()

    file.close()
    
    try:
	xsd_file=urllib2.urlopen("https://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd")
	output = open('TrainingCenterDatabasev2.xsd','w') 
	output.write(xsd_file.read().replace('\n',''))
	output.close()
	xsd_filename = "TrainingCenterDatabasev2.xsd"

	# Run some tests
	tree = objectify.parse(tcxFile)
	try:
	    schema = etree.XMLSchema(file=xsd_filename)
	    parser = objectify.makeparser(schema=schema)
	    objectify.fromstring(some_xml_string, parser)
	    print "YEAH!, your xml file has validated"
	except XMLSyntaxError:
        
	    print "Oh NO!, your xml file does not validate"
	    pass
	
    except urllib2.URLError:
	print "cannot download TCX schema"
	print "your TCX file is unvalidated. Good luck"

    
	    

    return 1

