from datetime import date, datetime
from services import *
from collections import defaultdict
import sys
CATEGORIES = ["populerkultur", "yazmevsimi", "kismevsimi", "yesilcam", "emojiler", "gol", "turkdizileri", "evlilik", "para", "kultursanat", "sesinicikar", "ikililer", "okul", "taklit", "osmanli", "markalar", "parti", "neyapiyorum", "ruhhali", "2000ler", "cizgifilm", "hayvanlar", "90lar", "sarkilar", "muzisyenler", "meslekler", "2015geyikleri", "superkahramanlar", "filmler", "diziler", "ankara", "vucudumuzutaniyalim", "yermekan", "mutfak", "istanbul", "sehirler", "2014", "spordunyasi", "oyunlar", "tarih", "futboltakimlari", "bayram", "2013", "teknolojibilgisayar"]
OPEN_KEY = "co.orkestra.nebuu.event.open"
PLAY_KEY = "co.orkestra.nebuu.event.play"
BUY_KEY = "co.orkestra.nebuu.event.buy"

def get_opens(rdb, start,end=None):

    OPEN_KEY = "co.orkestra.nebuu.event.open"

    start_s = int(datetime.strptime(start, '%d-%m-%Y').strftime('%s'))
    end_s = int(datetime.strptime(end, '%d-%m-%Y').strftime('%s')) if end else start_s+86399
    dspan = [start_s, end_s]

    load = lambda key: map(
            json.loads,
            rdb.smembers(key)
            )

    opens_raw = load(OPEN_KEY)
    opened = set(
            map(lambda e: e['uid'],
                filter(
                    lambda e: 'uid' in e and 'when' in e and dspan[0]<e['when']<dspan[1], 
                   opens_raw 
                    )
               )
            )

    return len(opened)

def get_stats(for_date):

    dspan = [int(datetime.strptime(for_date, '%d-%m-%Y').strftime('%s'))]
    dspan += [dspan[0]+86400]

    load = lambda key: map(
            json.loads,
            rdb.smembers(key)
            )

    opened = set(
            map(lambda e: e['uid'],
                filter(
                    lambda e: 'uid' in e and 'when' in e and dspan[0]<e['when']<dspan[1], 
                    load(OPEN_KEY)
                    )
               )
            )

    played = defaultdict(int)
    for e in []:#load(PLAY_KEY):
        try:
            assert(e['category'] in CATEGORIES)
            played[e['category']] += 1
        except: pass
    played['total'] = sum(played.values())

    return len(opened),played

if __name__ == '__main__':
    dt = sys.argv[1]
    try:
        dtt = sys.argv[2]
    except: dtt = None
    stats =  get_opens(dt, dtt)
    print 'opened:', stats[0]
