#!-*- coding:utf-8 -*-
import urllib
import urllib2
from urlparse import urlparse, urlunparse
from xml.dom import minidom
import xmllib
#import logging

use_google_api = False
try:
  from google.appengine.api import urlfetch
  use_google_api = True
except:
  pass

use_simplexml = False
try:
  import elementtree.SimpleXMLTreeBuilder as xmlbuilder
  use_simplexml = True
except:
  pass

class Response:
  def __init__(self, content):
    self.content = content

  def parse_xml(self):
    if use_simplexml:
      parser = xmlbuilder.TreeBuilder()
      xmllib.XMLParser.__init__(parser, accept_utf8=1)
      parser.feed(self.content)
      return parser.close()
    return minidom.parseString(self.content)

  def __str__(self):
    return self.content

class Simple:
  def __init__(self, opt):
    self.opt = opt

  def get(self, param = None, opt = None):
    url_param = urlparse(self.opt['base_url'])

    query_path = url_param[2]
    query_params = url_param[4]
    headers = {}

    if isinstance(opt, dict):
      if opt.has_key('path'):
        query_path += opt['path']
      if opt.has_key('headers'):
        headers.update(opt['headers'])

    if isinstance(self.opt, dict):
      if self.opt.has_key('param'):
        if len(query_params):
          query_params += "&"
        query_params += "%s" % urllib.urlencode(self.opt['param'])
      if self.opt.has_key('headers'):
        headers.update(self.opt['headers'])

    if isinstance(param, dict):
      query_params += "&%s" % urllib.urlencode(param)
    url = urlunparse(
        (url_param[0], url_param[1], query_path, url_param[3], query_params, url_param[5]))
    #logging.info(url)

    if use_google_api:
      return Response(urlfetch.fetch(url, headers=headers).content)

    return Response(urllib2.urlopen(urllib2.Request(url, headers=headers)).read())
