# -*- coding: iso-8859-1 -*-
u"""
    MoinMoin - ShowTweets macro Version 0.1 ALPHA
               Displays twitter messages (aka tweeds) from a user

    <<ShowTweets(user="UserName",maxTweets=10)>>
    
    Exampels: 
     * <<ShowTweets(user="UserName")>>
    
    @copyright: 2009 by MarcelHäfner (http://moinmo.in/MarcelHäfner)
    @license: GNU GPL, see COPYING for details.
    
    Licences for dependencies:
     * Python-Twitter is under Apache License, Version 2.0
     * simplejson is under MIT License

    Dependencies:
     * Python wrapper around the Python API (Python-Twitter): http://code.google.com/p/python-twitter/
     * JSON encoder/decoder for Python (simplejson) http://pypi.python.org/pypi/simplejson
    
    @TODO:
     1. Caching for the displayed tweets (because of limits: http://apiwiki.twitter.com/Rate-limiting) in memory of filesystem
     2. Authentication without cleartext passwd (maybe http://apiwiki.twitter.com/OAuth-FAQ)
     3. Better error handling for the urllib, not depending on sys and socket stuff
     4. Output of tweets as html and using some regular expressen to create working html links (for links and twitter references)
     5. Adding date/time to every tweet
     6. creating better error messages output
"""


from MoinMoin import wikiutil
from MoinMoin.formatter.text_html import Formatter
import twitter
import socket
import sys

def macro_ShowTweets(macro, user=u"Twitter",maxTweets=10, debug=False):

    #inital stuff
    socket.setdefaulttimeout(15)  # after 10s trying to fetch some data from the twitter-api, it will throw an exeption
    request = macro.request
    html_formatter = Formatter(request)
    _ = request.getText
    output = []
    errorMsg = []

    #user login
    #uncoment username and password, if you want to use it with username/password of your twitter own account 
    #but make make sure that nobody can read this macro and be aware of some possible security risks
    #username = "Your Username"
    #password = "Your Password"
    try:
        username
    except NameError:
       api = twitter.Api()
    else:
      api = twitter.Api(username=username, password=password) #ToDo: authentication without username/password, better security
    
    #just for testing to see the full error messages
    if debug == False:
        try:
            statuses = api.GetUserTimeline(wikiutil.escape(user))
        except: #ToDo: Should using Error message and not just all
            errorMsg.append('<div class="errormsg">')
            errorMsg.append(html_formatter.text(_("Twitter API error: %s") % sys.exc_info()[0]))
            errorMsg.append('</div>')
            return macro.formatter.rawHTML('\n'.join(errorMsg))
    else:
        statuses = api.GetUserTimeline(wikiutil.escape(user))

    #ToDo: Check if cache is avaible and don't ask twitter for every request

    #starting tweets output
    output.append(html_formatter.bullet_list(True))

    #reading tweets
    for tweetNumber in range(len(statuses)):      
        if tweetNumber < maxTweets:
            output.append(html_formatter.listitem(True))
            output.append(html_formatter.text(statuses[tweetNumber].text)) #ToDo: Output should be optimized with links
            output.append(html_formatter.listitem(False))
        else:
            break

    #check if there is atleast one tweet available
    if tweetNumber < 1:
        output.append(html_formatter.listitem(True))
        output.append(_("No tweet found"))
        output.append(html_formatter.listitem(False))

    #finishing tweets output
    output.append(html_formatter.bullet_list(False))      

    return ''.join(output)
