#!/usr/bin/python
# 
# blippy version 0.2
# @author Pawel 'Kender' Maczewski
# @email kender@codingslut.com
# License: you can use, distribute and modify this code, as long as your product won't be licensed under more restrictive conditions then stated here
# 2008
# 
# TODO: 
# 	* do bit more then this code does now
# 	* check the length of status / message to not try to send too long ones
# 
# 

import urllib, urllib2, base64, types
try:	
	import json
except ImportError:
	import simplejson as json 

updateTypes = ("updates", "directed_messages",) #  "private_messages")
class NoContent(Exception):
	pass

class Blip:
	
	def __init__(self, user, password):
		self.user = user
		self.password = password
	
	def __getRequest(self, url, post = None):
		x = urllib2.Request(url, post) # "http://api.blip.pl/updates", urllib.urlencode({"update[body]": status}))
		x.add_header('User-Agent', 'blippy')
		x.add_header('Accept', 'application/json')
		x.add_header('X-Blip-api', '0.02')
		x.add_header("Authorization", "Basic %s" % base64.b64encode("%s:%s" % (self.user, self.password)))
		
		return x

	def setStatus(self, status):
		r = None
		url = "http://api.blip.pl/updates"
		# try to handle status in either Unicode or UTF8 or ISO-8859-2...
		if type(status) == types.UnicodeType:
			post = urllib.urlencode({"update[body]": status.encode('utf-8')})
		else:
			try:
				post = urllib.urlencode({"update[body]": status.decode('iso-8859-2').encode('utf-8')})
			except UnicodeDecodeError:
				post = urllib.urlencode({"update[body]": status})
		x = self.__getRequest(url, post)
		try:
			r = urllib2.urlopen(x)
		except urllib2.HTTPError, e:
			if str(e).strip() != "HTTP Error 201: Created":
				print "r = ", r, " e = ", e
				raise e
	
	def sendDirectedMessage(self, target, message):
		# hungry dragon came eating the part of code to do it the right way...
		if type(message) == types.UnicodeType:
			m = u">%s: %s" % (target, message)
		else:
			try:
				m = (">%s: %s" % (target, message)).decode('utf-8')
			except UnicodeDecodeError:
				m = (">%s: %s" % (target, message)).decode('iso-8859-2')
		self.setStatus(m)
		return None

	def getUpdates(self, type = "", since = 0):
		if not type or type not in updateTypes:
			type = "updates"
		r = None
		if since:
			s = "/%s/since" % since
		else:
			s = ""
		x = self.__getRequest("http://api.blip.pl/" + type + s)
		try:
			r = urllib2.urlopen(x)
		except urllib2.HTTPError, e:
			if str(e).strip() == "HTTP Error 201: Created":
				pass
			elif str(e).strip() == "HTTP Error 204: No Content":
				return []
			else:
				print "r = ", r, " e = ", e
				raise e
		return json.loads(r.read())
	

