#!/usr/local/bin/python
"""
Mit GarminDB importierte Radfahr-activities in eine CSV-Datei schreiben 
"""
import argparse
import json
import os
import pandas as pd
from pandas import DataFrame, Series

import cols2drop

tours = []
df = DataFrame()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Write GarminDB cycling data to csv-file")
    parser.add_argument("activities_dir", type=str, help="directory of activities files")
    parser.add_argument("csv_file", type=str, help="output csv file", default='garmin_bike.csv')
    args = parser.parse_args()

    cnt = 0
    for subdir, dirs, files in os.walk(args.activities_dir):
        for file in files:
            filepath = subdir + os.sep + file
            if filepath.endswith(".json") and "#" not in filepath and "_details_" not in filepath and "_types" not in filepath :
                with open(filepath) as f:
                    activity_json = json.load(f)
                    if activity_json['activityType']['parentTypeId'] == 2: # Radfahren
                        activity_json['startTimeLocal'] = pd.to_datetime(activity_json['startTimeLocal'])
                        tours.append(activity_json)
                    cnt = cnt + 1
                    df = DataFrame(tours)
                    
    df.drop( cols2drop.cols2drop.split() , axis=1, inplace=True) # drop unnecessary columns
    
    df['distance'] = round(df['distance'], 3)
    df['maxSpeed'] = round(df['maxSpeed'], 2)
    df['averageSpeed'] = round(df['averageSpeed'], 4)
    df['elevationGain'] = round(df['elevationGain'],0)
    df['maxElevation'] = round(df['maxElevation'],0 )
    df['activityTrainingLoad'] = round(df['activityTrainingLoad'],0)
    df['movingDuration'] = round(df['movingDuration'], 0)
    df['duration'] = round(df['duration'], 0)
    df['distance'] = round(df['distance'], 0)

    df.to_csv(args.csv_file)

