
import datetime
from dateutil.relativedelta import relativedelta
import env
import logging
import mongoengine
from openrunlog import models
from tornado import ioloop, gen
import tornadotinyfeedback


def _daily_active_query():
    # TODO figure out why 27? timezones I'm guessing, still doesn't make sense
    yesterday = datetime.datetime.today()-relativedelta(hours=27)
    today_runs = models.Run.objects(date__gte=yesterday)
    users = set()

    for run in today_runs:
        users.add(run.user)
    num = len(users)
    return num


@gen.coroutine
def daily_active():
    logging.info('sending users.active.daily')
    yield gen.Task(tf.send, {'users.active.daily': _daily_active_query()})


def main():
    logging.info('starting active daily user counter')
    ioloop.PeriodicCallback(daily_active, 60*1000).start()


if __name__ == '__main__':
    config = env.prefix('ORL_')
    if config['debug'] == 'True':
        config['debug'] = True
    else:
        config['debug'] = False

    mongoengine.connect(
        config['db_name'],
        host=config['db_uri'])
    tf = tornadotinyfeedback.Client('openrunlog')
    logging.basicConfig(level=logging.INFO)

    logging.info('starting workers.metrics')
    main()

    ioloop.IOLoop.instance().start()

@@ -536,16 +536,342 @@
 n num%0A%0A%0A
+def _monthly_active_query():%0A    # TODO figure out why 27? timezones I'm guessing, still doesn't make sense%0A    monthly = datetime.datetime.today()-relativedelta(hours=27)%0A    runs = models.Run.objects(date__gte=monthly)%0A    users = set()%0A%0A    for run in runs:%0A        users.add(run.user)%0A    num = len(users)%0A    return num%0A%0A
 @gen.cor
@@ -881,28 +881,28 @@
 ine%0Adef 
-daily_
 active
+_users
 ():%0A    
@@ -1019,16 +1019,95 @@
 ery()%7D)%0A
+    yield gen.Task(tf.send, %7B'users.active.monthly': _monthly_active_query()%7D)%0A
 %0A%0Adef ma
@@ -1150,14 +1150,8 @@
 ive 
-daily 
 user
@@ -1189,28 +1189,28 @@
 allback(
-daily_
 active
+_users
 , 60*100

refactor daily active count to include montly active count