import json
from collections import Counter
from os import listdir
from os.path import exists

from datetime import datetime

from db import CassandraUtils

SAIDA_PATH = "/Users/Labtime/Dropbox/Twitter/Friends.Distributions/union.mat"
FRIENDS_PATH = "/Volumes/Seagate Expansion Drive/Twitter/friends/"

STR_DATE_FORMAT = "%b %d, %Y %I:%M:%S %p"

_cass = CassandraUtils()

def get_time(to_str=False):
    time = datetime.now()
    if to_str:
        return str(time)
    return time


def parse_date(str_date):
    return datetime.strptime(str_date, STR_DATE_FORMAT)


def handle_friends(friends):
    if friends is None or len(friends) == 0:
        return []
    return [r.friend_id for r in friends]


def handle_likes(likes):
    if likes is not None and len(likes) > 0:
        for like in likes:
            return [like['id'] for like in likes]
    return []


def handle_mentions(mt_tweets):
    vals = []
    if mt_tweets is not None and len(mt_tweets) > 0:
        for tweet in mt_tweets:
            vals.extend([me['id'] for me in tweet['userMentionEntities']])
    return vals


def handle_retweet(rt_tweets=None):
    if rt_tweets is not None and len(rt_tweets) > 0:
        return [tweet['retweetedStatus']['id'] for tweet in rt_tweets]
    return []


def print_(_file, line):
    _file.write('{0}\n'.format(line))


def handle_user(_user, _file=None):
    if _file is None:
        _file = '{0}{1}{2}'.format("/Users/Labtime/Documents/Data/", _user, '.json')
    if exists(_file):
        return

    likes = handle_likes(_cass.find_likes(_user))
    tweets = _cass.find_tweets(_user)
    mentions = handle_mentions(_cass.find_mentions(tweets=tweets))
    retweets = handle_retweet(_cass.find_retweets(tweets=tweets))

    with open(_file, 'w') as outfile:
        _line = json.dumps({_user: {'likes': likes, 'mentions': mentions, 'retweets': retweets}})
        outfile.write('{0}\n'.format(_line))

if __name__ == '__main__':
    lf = '/Users/Labtime/Dropbox/Twitter/Friends.Distributions/new_likes.json'
    mf = '/Users/Labtime/Dropbox/Twitter/Friends.Distributions/new_mentions.json'
    rf = '/Users/Labtime/Dropbox/Twitter/Friends.Distributions/new_retweets.json'
    uf = '/Users/Labtime/Dropbox/Twitter/Friends.Distributions/new_union.json'

    with open(SAIDA_PATH, 'r') as infile, open(lf, 'w') as lff, open(mf, 'w') as mff, open(rf, 'w') as rff, open(uf, 'w') as uff:
        i = 0
        for l in infile.readlines():
            user = int(json.loads(l).keys()[0])

            f_file = '{0}{1}{2}'.format("/Users/Labtime/Documents/Data/", user, '.json')

            friends = handle_friends(_cass.find_friends(user))
            if len(friends) > 0:
                for f in friends:
                    handle_user(_user=f)
            handle_user(_user=user, _file=f_file)
            i += 1
            print i, user, get_time(True)
                    # _likes = handle_likes(cass.find_likes(f))
                    # _tweets = cass.find_tweets(f)
                    # _mentions = handle_mentions(cass.find_mentions(tweets=_tweets))
                    # _retweets = handle_retweet(cass.find_retweets(tweets=_tweets))
                    # l = len(likes.intersection(_likes).union(likes.intersection(_retweets)))
                    # if l > 0:
                    #     fcl.update({int(f): l})
                    # m = len(mentions.intersection(_mentions))
                    # if m > 0:
                    #     fcm.update({int(f): m})
                    # r = len(retweets.intersection(_retweets).union(retweets.intersection(_likes)))
                    # if r > 0:
                    #     fcr.update({int(f): r})
                    # fcu = fcl + fcm + fcr
                # print_(lff, json.dumps({user: fcl}))
                # print_(mff, json.dumps({user: fcm}))
                # print_(rff, json.dumps({user: fcr}))
                # print_(uff, json.dumps({user: fcu}))
                #
                # lff.flush()
                # mff.flush()
                # rff.flush()
                # uff.flush()
