#coding: utf-8

from ..models.stats import ActiveTaxis
from ..extensions import redis_store, user_datastore, db, celery
from ..models.taxis import Taxi
from ..models.stats import ActiveTaxis
from itertools import izip, ifilter, imap
from datetime import datetime, timedelta
from time import mktime
from parse import parse as base_parse
from flask import current_app

def scan_as_list(match, redis_store):
    cursor = ''
    while cursor != 0:
        cursor, data = redis_store.scan(cursor=cursor, match=match, count=100)
        yield data

def filter_outoftime_values(operator_values, bound):
    f = lambda o_v: o_v[1] and o_v[1]['timestamp'] >= bound
    return filter(lambda operator_value: f(operator_value), operator_values)

def parse_operator_value(operator, s):
    if type(s) not in (str, unicode):
        return operator, None
    return operator, base_parse(Taxi._FORMAT_OPERATOR, s)

def get_data(taxi_ids, bound, redis_store):
    pipe = redis_store.pipeline()
    map(lambda k: pipe.hgetall(k), taxi_ids)
    parsed_values = map(lambda map_operator_v:\
        map(lambda o_v: parse_operator_value(*o_v), map_operator_v.iteritems()),
            pipe.execute())
    pipe.reset()
    filtered_value = map(lambda v: filter_outoftime_values(v, bound), parsed_values)
    zipped_value = izip(taxi_ids, filtered_value)
    return ifilter(lambda taxi_operator: len(taxi_operator[1]) > 0, zipped_value)

def store_active_taxis():
    current_app.logger.info('store_active_taxis')
    bound_time = datetime.now() - timedelta(minutes=15)
    bound = mktime(bound_time.timetuple())
    map_operateur_zupc_nb_active = dict()
    for l in scan_as_list('taxi:*', redis_store):
        for taxi_id, v in get_data(l, bound, redis_store):
            taxi_id = taxi_id[5:] #We cut the "taxi:" part
            taxi_db = Taxi.get(taxi_id)
            if taxi_db is None:
                current_app.logger.error('Taxi: {}, not found in database'.format(taxi_id))
                continue
            for operator, result in v:
                u = user_datastore.find_user(email=operator)
                if not u:
                    current_app.logger.error('User: {} not found'.format(operator))
                    continue
                if u.id not in map_operateur_zupc_nb_active:
                    map_operateur_zupc_nb_active[u.id] = dict()
                if taxi_db.ads.zupc_id not in map_operateur_zupc_nb_active[u.id]:
                    map_operateur_zupc_nb_active[u.id][taxi_db.ads.zupc_id] = 0
                map_operateur_zupc_nb_active[u.id][taxi_db.ads.zupc_id] += 1

    for operator, zupc_active in map_operateur_zupc_nb_active.iteritems():
        for zupc, active in zupc_active.iteritems():
            a = ActiveTaxis()
            a.nb_taxis = active
            a.operator_id = operator
            a.zupc_id = zupc
            a.timestamp = bound_time
            db.session.add(a)
    db.session.commit()


@@ -13,47 +13,8 @@
 -8%0A%0A
-from ..models.stats import ActiveTaxis%0A
 from
@@ -319,16 +319,104 @@
 rent_app
+%0Afrom influxdb import InfluxDBClient%0Afrom influxdb.exceptions import InfluxDBClientError
 %0A%0Adef sc
@@ -2638,236 +2638,605 @@
 = 1%0A
-%0A    for operator, zupc_active in map_operateur_zupc_nb_active.iteritems():%0A        for zupc, active in zupc_active.iteritems():%0A            a = ActiveTaxis()%0A            a.nb_taxis = active%0A            a.operator_id = operator%0A
+    client = InfluxDBClient('localhost', 8086, 'root', 'root', 'taxis')%0A    #try:%0A    #    client.create_database('taxis')%0A    #except InfluxDBClientError as e:%0A    #    if e%5B'content'%5D != u'database already exists':%0A    #        raise e%0A    to_insert = %5B%5D%0A    for operator, zupc_active in map_operateur_zupc_nb_active.iteritems():%0A        for zupc, active in zupc_active.iteritems():%0A            to_insert.append(%0A                %7B%0A                    %22measurement%22: %22nb_taxis%22,%0A                    %22tags%22: %7B%0A                        %22operator%22: user_datastore.get_user(operator).email,%0A          
     
@@ -3247,19 +3247,17 @@
     
-a.
+  %22
 zupc
-_id =
+%22:
  zup
@@ -3274,31 +3274,165 @@
     
-a.timestamp = bound_tim
+        %7D,%0A                    %22time%22: datetime.utcnow().strftime('%25Y%25m%25dT%25H:%25M:%25SZ'),%0A                    %22fields%22: %7B%0A                        %22value%22: activ
 e%0A  
@@ -3445,47 +3445,144 @@
     
-db.session.add(a)%0A    db.session.commit(
+        %7D%0A                %7D%0A            )%0A    current_app.logger.info('To insert: %7B%7D'.format(to_insert))%0A    client.write_points(to_insert
 )%0A
-%0A

Use influxDB