# -*- coding: utf-8 -*-

__author__ = "Yoan Blanc <yoan at dosimple dot ch>"
__revision__ = "20071110"
__license__ = "MIT"

import re
import logging

from tumblr import *
from jabberbot import JabberBot

class TumblrBot(JabberBot):
	"""Jabberbot for Tumblr"""
	
	regeces = {
		'commands': re.compile(r'(?P<command>(?:help)|(?:wtf)|(?:info))'),
		'quote': [
			re.compile(u'^ *« ?(?P<quote>[^()]*?) ?»'),
			re.compile(u'^ *“ ?(?P<quote>[^()]*?) ?”'),
			re.compile(u'^ *\' ?(?P<quote>[^()]*?) ?\''),
			re.compile(u'^ *" ?(?P<quote>[^()]*?) ?"'),
			re.compile(u'^ *„ ?(?P<quote>[^()]*?) ?“')],
		'link': re.compile(r'^ *(?P<title>.*?) *(?P<url>(?:(?:http://.+)|(?:www\..+))) *'),
		'html': re.compile(r'(?P<html>.*)', re.DOTALL),
		'title': re.compile(r'(?P<title>.*)'),
		'dialog': re.compile(r'^(?P<name>.*?): (?P<text>.*)$', re.MULTILINE)
	}
	
	def __init__(self, jid, password, users):
		super(TumblrBot, self).__init__(jid, password)
		self.users = users
		self._tumblrs = {}
	
	def getTumblr(self, jid):
		"""Return the Tumblr client for the given Jabber ID"""
		
		if not jid in self._tumblrs:
			user = self.users[jid]
			self._tumblrs[jid] = Tumblr( \
				user['nick'], \
				user['email'], \
				user['password'])
		
		return self._tumblrs[jid]
	
	def gotMessage(self, jid, body, resource):
		"""Getting the message from the client and posting on Tumblr"""
		
		logging.info(u"<<< %s: %s" % (jid, body))
		
		if jid in self.users:
			t = self.getTumblr(jid)
			post = self.parseMessage(body)
			
			if isinstance(post, Postable):
				header, resp = t.post(post)
				self.sendMessage(jid, u"%s posted (%s)." % (type(post).__name__, t.get_url(post)))
			else:
				if post == "help":
					self.sendMessage(jid, u"""Post your messages this way:

Regular:
 Title (mandatory)
 Text

Link:
 Title URL
 Text

Quote:
 “E=mc**2”
 Albert Einstein

Dialog:
 Title (mandatory)
 Joe: bla bla
 Nina: bli bli
""")
				elif post == "wtf":
					self.sendMessage(jid, u"EPIC FAIL!")
				elif post == "info":
					self.sendMessage(jid, u"%s by %s (revision: %s)" % (type(self).__name__, __author__, __revision__))
				else:
					self.sendMessage(jid, u"Did you say %s? I can't understand you." % (post))
		else:
			self.sendMessage(jid, u"I don't know you.")
	
	def sendMessage(self, to, body):
		"""Hook to JabberBot send message (adding log)"""
		
		logging.info(u">>> %s: %s" % (to, body))
		
		super(TumblrBot, self).sendMessage(to, body)
	
	def parseMessage(self, message):
		if message.find("\n") >= 0:
			title, body = message.split("\n", 1)
			
			# Quote
			for regex in self.regeces['quote']:
				match = regex.match(title)
				if match:
					return Quote(match.group("quote"), body)
			
			# Link
			match = self.regeces['link'].match(title)
			if match:
				return Link(match.group("url"), match.group("title"), body)
			
			# Dialog
			match = self.regeces['dialog'].match(body)
			if match:
				if self.regeces['dialog'].match(title):
					return Conversation("\n".join(title, body))
				elif body.find("\n") >= 0:
					# Testing that several lines of the dialog are in a dialog format
					dialog = body.split("\n")
					counter = 0
					for line in dialog:
						if self.regeces['dialog'].match(line):
							counter += 1
					if counter >= len(dialog)/2:
						return Conversation(body, title)
			
			# Regular
			if body:
				return Regular(body, title)
		else:
			# Commands
			match = self.regeces['commands'].match(message)
			if match: 
				return match.group("command")
			
			return Regular(message)

