#!/usr/bin/env/python

"""
Takes the file generated by get_tweets.py 
and assigns each twitter handle a numeric value and
sorts all tweet events by their time
"""
import argparse
import time
import sys

from common import *
from datetime import datetime

curr_uid = 2
handle_to_uid = {}

def get_uid_for_handle(handle, leader_handle):
  global curr_uid
  global handle_to_uid
  if handle == "-1":
    return 0
  #If its already in int id format, don't need to do anything.
  if handle.isdigit():
    return handle
  if handle == leader_handle:
    return 1
  if handle in handle_to_uid:
    return handle_to_uid[handle]
  handle_to_uid[handle] = curr_uid
  curr_uid += 1
  return handle_to_uid[handle]

def main(args):
  tweet_events = []
  with open(args.tweets_file, 'r') as tweets_file:
    with open(args.output, 'wb') as output:
      for line in tweets_file:
        line = line.strip('\n')
        line = line.split(",")        
        follower_uid = get_uid_for_handle(line[1], args.leader_handle)
        celebrity_uid = get_uid_for_handle(line[2], args.leader_handle)
        tweet_events.append((long(line[0]), str(follower_uid), str(celebrity_uid)))
        
      tweet_events = sorted(tweet_events, key = lambda (timestamp, fid, cid): timestamp)
      for tweet in tweet_events:
        output.write(str(tweet[0]) + "," + tweet[1] + "," + tweet[2]+"\n")


if __name__ == "__main__":
  parser = argparse.ArgumentParser(description='Specify arguments')
  parser.add_argument('--leader_handle', help='handle of the leader node', required=True)
  parser.add_argument('--tweets_file', help='the tweets file produced by get_tweets.py', required=True)
  parser.add_argument('--output', help='the output file', required=True)

  args = parser.parse_args()

  start_time = time.time()
  main(args)
  end_time = time.time()
  print "Minutes elapsed", (end_time-start_time)/60
  main(args)