#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import twitter

from genshi.builder import tag

from trac.core import *
from trac.admin.api import IAdminPanelProvider
from trac.ticket.api import ITicketChangeListener
from trac.config import Option

class TracTwitterPlugin(Component):
    implements( ITicketChangeListener )

    password = Option('twitter', 'password', '', u'パスワード' )
    username = Option('twitter', 'username', '', u'ユーザー名' )

    # ITicketChangeListener methods
    """Extension point interface for components that require notification
    when tickets are created, modified, or deleted."""

    def ticket_created( self, ticket ):
        """Called when a ticket is created.
        """
        self.post_message( ticket, ticket["reporter"], u"チケットを作成しました" )

    def ticket_changed( self, ticket, comment, author, old_values ):
        """Called when a ticket is modified.

        `old_values` is a dictionary containing the previous values of the
        fields that have changed.
        """
        self.post_message( ticket, author, u"チケットを更新しました", comment )

    def ticket_deleted( self, ticket ):
        """Called when a ticket is deleted."""
        pass

    def post_message(self, ticket, author, operation, comment = ""):
        message = author + u" が"
        message += operation + u" : "
        message += ticket.env.project_name + u" - "
        message += u"#" + str( ticket.id )
        message += u" "
        message += u"(" + ticket["summary"] + u")"
        message += u" "
        message += comment + u" "
        message += self.env.project_url + "/ticket/" + str( ticket.id )

        api = twitter.Api( self.username.encode('ascii'), self.password.encode('ascii') )
        status = api.PostUpdate( message )
