from requests_oauthlib import OAuth1Session
import argparse

import json


from datetime import datetime
#import dateutil.tz
import pytz

import logging
import sys

from kametwi.settings import Settings

"""
This is a command line tool of watching twitter timelines
"""
__status__ = "production"
__date__ = "11 Apr 2015"

logger = logging.getLogger(__name__)

# Set REST API URL
HOME_TIME_LINE_URL = 'https://api.twitter.com/1.1/statuses/home_timeline.json'
USER_TIME_LINE_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
POST_STATUS_UPDATE = 'https://api.twitter.com/1.1/statuses/update.json'

# Set twitter keys
CK = Settings.TWITTER_KEYS['CK']
CS = Settings.TWITTER_KEYS['CS']
AT = Settings.TWITTER_KEYS['AT']
AS = Settings.TWITTER_KEYS['AS']

# Set timezone
tz_tokyo = pytz.timezone(Settings.TIME_ZONE)


def main():

    # Get args
    



# Get someone's timeline
def show_user_timeline(oauth,args):
    params = {"screen_name":args.screen_name}
    req = oauth.get(USER_TIME_LINE_URL, params = params)

    # Check response
    if req.status_code == 200:
        timeline = json.loads(req.text)
    else:
        print ("Error: %d" % req.status_code)

    timeline.reverse()

    # display timeline
    for tweet in timeline:

        dt = datetime.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')
        #dt.replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzlocal())
        created_at = tz_tokyo.fromutc(dt).strftime('%Y-%m-%d %H:%M:%S')
        print('[{created_at}] {message}'.format(created_at=created_at,
                                              message=tweet["text"]))


def show_home_timeline(oauth):
    params = {}
    req = oauth.get(HOME_TIME_LINE_URL, params = params)

    # Check response
    if req.status_code == 200:
        timeline = json.loads(req.text)
    else:
        print ("Error: %d" % req.status_code)

    timeline.reverse()

    # display timeline
    for tweet in timeline:
        # i.g. Sat Apr 11 06:10:12 +0000 2015
        dt = datetime.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')
        #dt.replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzlocal())
        created_at = tz_tokyo.fromutc(dt).strftime('%Y-%m-%d %H:%M:%S')

        print('[{created_at}] @{screen_name}: {message}'.format(created_at=created_at,
                                                                screen_name=tweet["user"]["screen_name"],
                                                                message=tweet["text"]))


def post_tweet(oauth,args):
    params = {"status":args.tweet}
    req = oauth.post(POST_STATUS_UPDATE, params = params)

    # Check response
    if req.status_code == 200:
        print("OK")
    else:
        print("Error: {status_code}".format(req.status_code))

# main flow
if __name__ == '__main__':
    sys.exit(main())
parser = argparse.ArgumentParser(description='twitter command line tool')
    parser.add_argument('command')
    parser.add_argument('-s', '--screen_name')
    parser.add_argument('-t', '--tweet')
    parser.add_argument('-v')    # Display the request body
    parser.add_argument('--version', action='version', version='%(prog)s 2.0')

    args = parser.parse_args()

    # OAuth
    oauth = OAuth1Session(CK, CS, AT, AS)

    if args.command == "home":
        show_home_timeline(oauth)
    elif args.command == "timeline":
        show_user_timeline(oauth,args)
    elif args.command == "tweet":
        post_tweet(oauth,args)
    else:
        show_home_timeline(oauth)