#!/usr/bin/env python
import time
import json
import argparse
from datetime import datetime
from chrono import *
from config import *
from clients import *


def query_current_active_user():
    """
    get current active users.

    :return:  list like: [168001, 168002]
    """
    db = conn_mysql(my_host, my_port, my_user, my_password, my_database_platm)
    cs = db.cursor()

    td = ts_today()
    std = str_today(td)
    sql = 'SELECT DISTINCT(guid) AS guid FROM {} where start_time>"{}"'.format(my_tbl_history, std)
    print(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'), sql)
    cs.execute(sql)
    rs = cs.fetchall()

    cs.close()
    db.close()
    return [r[0] for r in rs]


def redis_update_active_user(users):
    """
    update active users into redis

    :param users: like [168001, 168002]
    :return: None
    """
    fmt = {
        'ts': int(ts_now()),
        'gameId': 0,
        'balance': 0,
        'history': [{
            'gameId': 0,
            'delta': 0,
        }]
    }
    value = json.dumps(fmt)

    rds = conn_redis(rds_host, rds_port, '', rds_password, 8)
    for user in users:
        rds.hset(rds_key_ua, str(user), value)
    rds.close()


def main():
    """ simple work flow

    ignores any exceptions but restarted automatically by supervisor

    Usage:
    python -u $FILENAME -i 360
    > witch -i means interval in seconds, 600s(10min) by default.
    """
    parser = argparse.ArgumentParser(description='timer task for checking if user active')
    parser.add_argument('-i', '--interval', action='store', dest='interval', default=600, type=int, metavar='interval', help='set interval of execution')
    args = parser.parse_args()

    while True:
        users = query_current_active_user()
        redis_update_active_user(users)
        time.sleep(args.interval)


if __name__ == '__main__':
    main()
