import datetime as dt
from TwitterSearch import TwitterSearch, TwitterUserOrder
import json
import sys
import twitter


MAX_TWEETS=5900

def gather_tweets(handle, filename):
    '''
    Simple function for gathering tweets from the specified handle.
    Stores the results as JSON in the specified file.
    '''
    # Taken from https://pypi.python.org/pypi/TwitterSearch/
    tweets = []
    count = 0
    try:
        consumer_credentials = open("./.consumer-credentials")
        consumer_token, consumer_secret = consumer_credentials.read().strip().split()

        user_credentials = './.twitter-credentials'
        oauth_token, oauth_secret = twitter.read_token_file(user_credentials)

        tuo = TwitterUserOrder(handle)

        ts = TwitterSearch(
            consumer_key = consumer_token,
            consumer_secret = consumer_secret,
            access_token = oauth_token,
            access_token_secret = oauth_secret)
        
        # start asking Twitter about the timeline
        for tweet in ts.search_tweets_iterable(tuo):
            tweets.append(tweet)
            count = count + 1
            if count == MAX_TWEETS:
                break
            
    except Exception as e: # catch all those ugly errors
        print(e)

    with open(filename, "w") as f: 
        json.dump(tweets, f)

