# -*- coding: iso-8859-1 -*-
u"""
    MoinMoin - ShowTweets macro Version 0.3.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. Better 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 (not wiki like now) and using some regular expressen to create working html links (for links and twitter references)
"""


from MoinMoin import wikiutil
from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
import twitter
import socket
import sys

Dependencies = [] #do cache

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
    fmt = macro.formatter
    _ = request.getText
    output = []
    errorMsg = []

    #user login
    #uncoment username and password, if you want to use it with username/password of your twitter own account 
	#The twitter.Api instance must be authenticated if the user is private.
    #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(user=wikiutil.escape(user),count=maxTweets)
        except: #ToDo: Should using Error message and not just all
            errorMsg.append(fmt.div(True,css_class="error"))
            errorMsg.append(fmt.text(_("Twitter API error: %s") % sys.exc_info()[0]))
            errorMsg.append(fmt.div(False))
            return ''.join(errorMsg)
    else:
        statuses = api.GetUserTimeline(user=wikiutil.escape(user),count=maxTweets)

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

    #starting tweets output
    output.append(fmt.div(True,css_class="ShowTweets"))
    output.append(fmt.bullet_list(True))

    #reading tweets
    for tweetNumber in range(len(statuses)):
        output.append(fmt.listitem(True))
        output.append(wikiutil.renderText(request, WikiParser, statuses[tweetNumber].text))
        output.append(fmt.span(True,css_class="date",style="color:Gray; font-size:75%; display:block;"))
        output.append(fmt.text(statuses[tweetNumber].created_at))
        output.append(fmt.span(False))
        output.append(fmt.listitem(False))

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

    #finishing tweets output
    output.append(fmt.bullet_list(False))
    output.append(fmt.div(False))

    return ''.join(output)
