import os
import string
import StringIO

from quixote import get_response, get_request

from compClust.config import config

from simpletal import simpleTAL, simpleTALES, simpleTALUtils
talCache = simpleTALUtils.TemplateCache()

def setXHTMLtype():
  get_response().set_content_type('text/html')
  
  #if 'application/xhtml+xml' in get_request().get_accepted_types():
  #  get_response().set_content_type('application/xhtml+xml')
  #else:
  #  get_response().set_content_type('text/html')

def template_header(datamagerui):
  return '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>Comp Clust</title>
  <link rel="stylesheet" href="%(compclust_css)s" type="text/css" />
</head>
<body>''' % {"compclust_css": _path_join(datamagerui.root_url, 'compclust_css')}

def template_footer():
  return '</html>'

def get_template(filename, context=None):
  if context is None:
    context = simpleTALES.Context()
    
  page = StringIO.StringIO()
  setXHTMLtype()
  template_pathname = os.path.join(config.template_dir,filename+'.xml')
  template= talCache.getXMLTemplate(template_pathname)
  template.expand(context, page)
  return page.getvalue()

def _path_join(*args):
  """Abstract out the os.path.join as the '/' as path seperator is a unix-ism
  """
  return string.join(args, '/')

