# -*- coding: iso-8859-1 -*-
u"""
    MoinMoin - ShowTweets macro Version 0.6.1
               Displays twitter messages (aka tweeds) from a user

    <<ShowTweets(user="Twitter Username", maxTweets=10, noReply=True)>>

    Exampels:
     * <<ShowTweets(rockheavy)>>

    Notes about OAuth:
    All Twitter apps/clients are required to use secure authentication based on OAuth.
    You need to registry this app on https://dev.twitter.com/apps and get from theire the consumer secret / key.

    @copyright: 2009 by MarcelHäfner (http://moinmo.in/MarcelHäfner)
    @license: GNU GPL, see COPYING for details.

    Licences for dependencies:
     * tweepy is under MIT License

    Dependencies:
     * python-tweepy [[https://github.com/tweepy/tweepy]]

    Version:
     * 0.6.1: Bugfix (typo)
     * 0.6: Fixed error to get another users timeline (user -> user_id)
     * 0.5 / 03.01.2013: Moved to Tweepy. Integrated Patch from FelixYan to add an option to hide @replies from results

"""
from MoinMoin import wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
import tweepy
import socket
import sys

Dependencies = ['time']  # do not cache; or cache and remove the 'time'


def errorOutput(macro, errorType, errorMessage):
    """
    Return a rendered error message
    @param errorType: some main error type
    @param errorMessage: detail error type
    @returns: list
    """
    request = macro.request
    fmt = macro.formatter
    _ = request.getText

    errorMsg = []
    errorMsg.append(fmt.div(True, css_class="error"))
    errorMsg.append(wikiutil.renderText(request, WikiParser, _("/!\ Error Message from Macro [[http://moinmo.in/MacroMarket/ShowTweets|ShowTweets]]!")))
    errorMsg.append(fmt.bullet_list(True))
    errorMsg.append(fmt.listitem(True))
    errorMsg.append(fmt.text(_("Type: %s") % wikiutil.escape(errorType).decode("utf-8", "replace")))
    errorMsg.append(fmt.listitem(False))
    errorMsg.append(fmt.listitem(True))
    errorMsg.append(fmt.text(_("Message: %s") % wikiutil.escape(errorMessage)))
    errorMsg.append(fmt.listitem(False))
    errorMsg.append(fmt.bullet_list(False))
    errorMsg.append(fmt.div(False))
    return ''.join(errorMsg)


def macro_ShowTweets(macro, user, maxTweets=10, noReply=True):
    """
    Creates a ordered list with twitter status messages
    @param user: username from a twitter account, needed
    @param maxTweets: optional, how many tweets should be displayed
    """

    #Inital stuff
    socket.setdefaulttimeout(10)  # timeout set to 10s
    request = macro.request
    fmt = macro.formatter
    _ = request.getText
    output = []
    tweetNumber = 0
    #user = "<twitteraccount>"

    #OAUTH configuration (you have to configure this!)
    consumer_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    consumer_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    access_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    access_token_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    #Initi the API
    api = tweepy.API(auth,secure=True)

    #Fetch more for filtering
    fetchNum = maxTweets
    if noReply:
        fetchNum *= 10

    #Get the messages from twitter or use an exception to display an error msg
    try:
        statuses = api.user_timeline(id=wikiutil.escape(user), count=fetchNum)
    except:
        return errorOutput(macro, _("GetUserTimeline"), str(sys.exc_info()[1]))

    #Starting tweets output
    output.append(fmt.div(True, css_class="ShowTweets"))
    output.append(fmt.bullet_list(True))

    #Reading tweets
    tweetCount = 0
    for tweet in statuses:
        if noReply and tweet.text[0] == "@":
            continue
        output.append(fmt.listitem(True))
        output.append(wikiutil.renderText(request, WikiParser, wikiutil.escape(tweet.text)))
        output.append(fmt.span(True, css_class="date", style="color:Gray; font-size:75%; display:block;"))
        output.append(fmt.text(wikiutil.escape(statuses[tweetNumber].created_at)))
        output.append(fmt.span(False))
        output.append(fmt.listitem(False))
        tweetCount += 1
        if tweetCount >= maxTweets:
            break

    #Check if there is atleast one tweet available for ouput
    if tweetCount < 1:
        return errorOutput(macro, _("tweetNumber"), _("Can't find any twitter status message from user '%s'" % user))

    #Finishing output
    output.append(fmt.bullet_list(False))
    output.append(fmt.div(False))
    return ''.join(output)
