#!/usr/bin/env python3

import sys
import os
from analyzer import Analyzer
from twython import Twython
from twython import TwythonAuthError, TwythonError, TwythonRateLimitError
from analyzer import Analyzer
from termcolor import colored

# get user tweets
def get_user_timeline(screen_name, count=50):
    """Return list of most recent tweets posted by screen_name."""

    # ensure count is valid
    if count < 1 or count > 50:
        raise RuntimeError("invalid count")

    # ensure environment variables are set
    if not os.environ.get("API_KEY"):
        raise RuntimeError("API_KEY not set")
    if not os.environ.get("API_SECRET"):
        raise RuntimeError("API_SECRET not set")

    # get screen_name's (or @screen_name's) most recent tweets
    # https://dev.twitter.com/rest/reference/get/users/lookup
    # https://dev.twitter.com/rest/reference/get/statuses/user_timeline
    # https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py
    try:
        twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET"))
        user = twitter.lookup_user(screen_name=screen_name.lstrip("@"))
        if user[0]["protected"]:
            return None
        tweets = twitter.get_user_timeline(screen_name=screen_name, count=count)
        # return tweets
        return [tweet["text"].replace("\n", " ") for tweet in tweets]

    except TwythonAuthError:
        raise RuntimeError("invalid API_KEY and/or API_SECRET") from None
    except TwythonRateLimitError:
        raise RuntimeError("you've hit a rate limit") from None
    except TwythonError:
        return None

# check for valid argument
if len(sys.argv) != 2:
    sys.exit("Usage: ./tweets @screen_name")
# initialize analyze object
analyzer = Analyzer(os.path.join(sys.path[0], "positive-words.txt"),
            os.path.join(sys.path[0], "negative-words.txt"))
# get all the tweet
tweets = get_user_timeline(sys.argv[1])
# iterate through the tweets and print the result
for i in tweets:
    if analyzer.analyze(i) > 0.0:
        print(colored(":) {}".format(i), "green"))
    elif analyzer.analyze(i) < 0.0:
        print(colored(":( {}".format(i), "red"))
    else:
        print(colored(":| {}".format(i), "yellow"))
