# -*- coding: utf-8 -*-
import simplejson, sys, datetime
import moving, utils
from pyproj import Proj

import matplotlib.pyplot as plt
import matplotlib.mlab as pylab
import numpy as np
import pandas as pd

#notes = [f['properties']['notes'] for f in data['features'] if len(f['properties']['notes']) > 0]

english2French = {'Commute': 'Domicile-travail',
                  'Errand': 'Courses',
                  'Exercise': 'Sport',
                  'Leisure': 'Loisirs',
                  'Other': 'Autre',
                  'Autres': 'Autre',
                  'Autres motifs': 'Autre',
                  'School': u'École',
                  'Shopping': 'Magasinage',
                  'Work-Related': 'Travail',
                  'Work-related': 'Travail',
                  'Other': 'Autre',
                  'other': 'Autre'}

odMotifs = ['Magasinage', 'Retour au domicile', "Chercher quelqu'un",
            'Travail ', '\xc9tude / \xc9cole', 'Autre', 'Loisir',
            "Visites d'ami(e)s et/ou de la parent\xe9", "Reconduire quelqu'un",
            "Rendez-vous d'affaires", 'Sant\xe9',
            'Ind\xe9termin\xe9 / refus / NSP']

def convertJsonToMTM(data = None, filename = None):
    'Converts the in put json data to MTM and optionally saves to file'
    proj = Proj(init="epsg:2950")
    if data is None:
        data = simplejson.load(open(filename))
    for i in xrange(len(data['features'])):
        latlon = data['features'][i]['geometry']['coordinates']
        mtm = [proj(p[0], p[1]) for p in latlon]
        data['features'][i]['geometry']['coordinates'] = mtm
    if filename is not None:
        simplejson.dump(data, open(utils.removeExtension(filename)+'-mtm.json', 'w'))
    return data

def convertToObjects(data, timeStep = 1, project = True, minLength = 10):
    'Converts the trips to the moving.MovingObject class from Traffic Intelligence'
    if project:
        proj = Proj(init="epsg:2950")
    objects = []
    nTrips = len(data['features'])
    for i in xrange(nTrips):
        latlon = data['features'][i]['geometry']['coordinates']
        if project:
            projectedX = [proj(p[0], p[1]) for p in latlon[::timeStep]]
        else:
            projectedX = latlon[::timeStep]
        o = moving.MovingObject(num = i, positions = moving.Trajectory(np.array(projectedX).T.tolist()))
        o.properties = data['features'][i]['properties']
        o.motif = english2French.get(o.properties['purpose'], o.properties['purpose'])
        try:
            o.start = datetime.datetime.strptime(o.properties['start'], '%Y-%m-%d %H:%M:%S')
            o.stop = datetime.datetime.strptime(o.properties['stop'], '%Y-%m-%d %H:%M:%S')
            if o.positions.length() > minLength:
                objects.append(o)
        except TypeError:
            print('{} {}'.format(o.properties['start'], o.properties['stop']))
            print('issue with {}'.format(o.properties))
            #o.start = datetime.datetime(1979, 7, 21)
            #o.stop = o.start
            #print(e)
    return objects

filename = './trip5000.json'
data = simplejson.load(open(filename))
# od = pd.read_csv('/home/nicolas/tmp/defivelomtl/velo-od-2013/od13niv2 - Résident MTL avec vélo.csv', delimiter = ';')

#convertJsonToMTM(data)
#objects = convertToObjects(data, project = False, minLength = 10)
objects = convertToObjects(data, minLength = 10)
colors = utils.PlottingPropertyValues('rk')

def printMRV(objects, motifs, color, linewidth, alpha, blackBG = False):
    fig = plt.figure()
    for o in objects:
        if o.motif in motifs:
            o.plot(color, linewidth = linewidth, alpha = alpha)
    plt.axis('equal')
    plt.axis('off')
    plt.tight_layout()
    if blackBG:
        fig.patch.set_facecolor('black')
        plt.savefig(u'mrv-'+u'-'.join(motifs).replace(' ', '-')+'-'+color+'-blackbg.png', dpi = 300, facecolor=fig.get_facecolor(), edgecolor='none')
    else:
        plt.savefig(u'mrv-'+u'-'.join(motifs).replace(' ', '-')+'-'+color+u'.png', dpi = 300)

for i, m in enumerate(allmotifs):
    printMRV(objects, [m], colors[i], 0.5, 0.1)

printMRV(objects, ['Aller au travail', 'Domicile-travail'], 'k', 0.5, 0.1)
printMRV(objects, ['Travail', u'D\xe9placement professionnel'], 'k', 0.5, 0.1)
printMRV(objects, ['Aller au travail', 'Domicile-travail', 'Travail', u'D\xe9placement professionnel'], 'k', 0.5, 0.1)

# generate an enriched json with added data
generateJSON = False
if generateJSON:
    for o in objects:
        o.positions.computeCumulativeDistances()

#properties = {'length': [],
#              'wiggliness': []}

    removeBothEnds = 2
    # export mean speed, nseconds, wiggliness, speeds, accel
    for o in objects:
        #print o.positions.length(), (o.stop-o.start).seconds, (o.stop-o.start).seconds/float(o.positions.length()), o.positions.wiggliness()
        #print o.positions.length(), o.properties['n_coord'], len(o.positions.differentiateSG(5,2,2)), len(o.positions.differentiateSG(5,2,1))
        speeds = o.positions.differentiateSG(5,2,1, removeBothEnds = removeBothEnds).norm().tolist()
        accel = o.positions.differentiateSG(5,2,2, removeBothEnds = removeBothEnds).norm().tolist()
        data['features'][o.getNum()]['properties']['speeds'] = [speeds[0]]*removeBothEnds+speeds+[speeds[-1]]*removeBothEnds
        data['features'][o.getNum()]['properties']['accelerations'] = [accel[0]]*removeBothEnds+accel+[accel[-1]]*removeBothEnds
        data['features'][o.getNum()]['properties']['n_points'] = o.positions.length()
        data['features'][o.getNum()]['properties']['n_seconds'] = (o.stop-o.start).seconds
        data['features'][o.getNum()]['properties']['mean_speed'] = o.positions.cumulativeDistances[-1]/data['features'][o.getNum()]['properties']['n_seconds']
        data['features'][o.getNum()]['properties']['wiggliness'] = o.positions.wiggliness()

    nums = [o.getNum() for o in objects]
    data['features'] = [d for i, d in enumerate(data['features']) if i in nums]
    simplejson.dump(data, open(utils.removeExtension(filename)+'-enriched.json', 'w'))
