#!/usr/bin/env python
# wsgi service
import os
import util
import htmllib
import cgi

#---------------GENERAL HTML FUNCTION------------------------
def unescape(s):
    """Convert HTML entities back to normal text"""
    p = htmllib.HTMLParser(None)
    p.save_bgn()
    p.feed(s)
    return p.save_end()

#----------------BASE-----------------------------------------
class DBlock(util.StackListDict):
  """Base class of HTML page, derive from util.StackListDict
  """

  def __init__(self, template=""):
    self.template = template
    util.StackListDict.__init__(self)

  def read_template(self, filename=""):
    if filename and os.path.exists(filename):
      f = open(filename)
      txt = f.read()
      f.close()
      if txt:
        self.template = txt

  def get_template(self):
    """Template of block inner property, may be overidden"""
    if self.template == "":
      txt = ""
      for i in self.keys():
        txt += '<div id="%s"><?py print _%s ?></div>\n' % (i, i)
      return txt
    else:
      return self.template

  def get_content(self):
    if self.template is None or self.template == "":
      template = self.get_template()
    else:
      template = self.template
    for i in self.keys():
      exec '_%s = ""' % (i,)
      n = 0
      for j in self[i]:
        if type(self[i][n]) == type(""):
          exec '_%s += self[i][n]' % (i,)
        else:
          if hasattr(self[i][n], "get_content"):
            temp = self[i][n].get_content()
          else:
            temp = str(self[i][n])
          exec '_%s += temp' % (i,)
        n += 1

    txt = ""
    while '<?py ' in template:
      front, template = template.split('<?py ',1)
      txt += front
      if '?>' in template:
        pycmd, template = template.split(' ?>', 1)
        pycmd = pycmd.strip()
        if "print " in pycmd:
          pycmd = pycmd.replace("print ","txt += ")
        try:
          exec "%s" % (pycmd)
        except NameError:
          pass
        except:
          txt += "DEBUG---%s NOT FOUND---DEBUG" % (pycmd,)
    return txt+template

  def content(self):
    return self.get_content()

  def show(self):
    print self.get_content()


#-------------------WSGI---------------------------------------------
#CGI & WSGI 
def get_FieldStorage(environ=None):
    "FieldStorage value from method POST"
    if environ is not None:
        if environ["REQUEST_METHOD"].upper() == "GET":
            qs = environ["QUERY_STRING"]
        else:
            qs = environ["wsgi.input"].read()
        d = cgi.parse_qs(qs)
        return d
    else:
        return {}

