import cgi
import time
import httplib
import urllib
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from StringIO import StringIO
from ConfigParser import RawConfigParser
from feedformatter.feedformatter import Feed
try:
  from xml.etree.cElementTree import XML
except ImportError:
  from xml.etree.ElementTree import XML

###########################
# Setup (config, logging) #
###########################
_defaults = {
  'tumblr': {
             'email': 'example@example.com',
             'password': 'example',
            },
  'feed': {
           'title': 'My Dashboard Feed',
           'description': 'My Tumblr Dashboard feed',
           'img_size': 0,
          },
            }

_config = RawConfigParser(_defaults)
_config.read('config.ini')

#############
# Functions #
#############
def fetch_tumblr_dashboard_xml(email,password):
  """Implements a Tumblr Dashboard API read
  
  :param string email: Tumblr account email address
  :param string password: tumblr account password
  """
  
  # Prepare POST request
  params = urllib.urlencode([('email',email),('password',password),
                             ('generator','Tumblr Dashboard Reader'),
                             ('num','50')])
  headers = {"Content-type": "application/x-www-form-urlencoded",
             "Accept": "text/plain"}
  
  connection = httplib.HTTPConnection("www.tumblr.com")
  connection.request("POST", "/api/dashboard", params,headers)
  response = connection.getresponse()
  connection.close()
  
  if str(response.status) == '200':
    return (True, response.read())
  else:
    return (False,'Connection failed. Response %s, %s' % (response.status, response.reason))

def xml_to_atom(xml,feedtitle,feeddescription,feedurl,authoremail,img_size=0):
  """Transform the XML from Tumblr into an Atom feed.
  
  :param string xml: Raw XML returned from Tumblr
  :param string feedtitle: Title of the atom feed
  :param string feeddescription: Description of the atom feed
  :param string feedurl: URL that will contain the feed
  :param int img_size: Size of images to include; 0-5 (0 is original, 5 is small)
  :returns: The Atom feed's XML
  """
  # Make sure parameters are "good"
  if feedurl.endswith('atom.xml'):
    pass
  elif feedurl[-1] == '/':
    feedurl = feedurl+'atom.xml'
  else:
    feedurl = feedurl+'/atom.xml'
  
  if type(img_size) is not int:
    img_size = int(img_size)
  
  # Set up the Atom feed
  atom = Feed()
  atom.feed["title"] = feedtitle
  atom.feed["description"] = feeddescription
  atom.feed["id"] = feedurl
  atom.feed["link"] = {'_href': feedurl,
                       '_rel': 'self',
                       '_type': 'application/atom+xml'}
  atom.feed["generator"] = {'_uri': "http://github.com/tbekolay/Tumblr-Dashboard-Feed",
                            '_version': '0.1',
                            'text': 'Tumblr Dashboard Reader'}
  atom.feed["icon"] = "http://assets.tumblr.com/images/favicon.gif"
  atom.feed["logo"] = "http://assets.tumblr.com/images/logo.png"
  atom.feed["author"] = {'name':authoremail.split('@')[0], 'email':authoremail}
  atom.feed["updated"] = time.gmtime()
  
  # Start parsing the XML file
  et = XML(xml)
  posts = et.find('posts')
  
  for post in posts.findall('post'):
    # Information common to all types
    item = {}
    item["id"] = post.attrib.get('url-with-slug')