#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
from lxml import etree
from translationInfo import getTranslatorSource


import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../common/gae/libs'))
from misc import isGoogleAppEngine
from misc import isProductionServer

if isGoogleAppEngine():
  if isProductionServer():
    paliXmlUrlPrefix = u'http://epalitipitaka.appspot.com/romn/'
    trXmlUrlPrefix = u'http://epalitipitaka.appspot.com/translation/'
  else:
    #paliXmlUrlPrefix = os.path.join(os.path.dirname(__file__), 'romn')
    #trXmlUrlPrefix = os.path.join(os.path.dirname(__file__), 'translation')
    paliXmlUrlPrefix = u'http://localhost:8080/romn/'
    trXmlUrlPrefix = u'http://localhost:8080/translation/'
else:
  # add amazon ec2 support here
  raise Exception('currently only Google App Engine is supported')


if isGoogleAppEngine():
  xslt_root = etree.parse(os.path.join(
                paliXmlUrlPrefix, 'cscd/tipitaka-latn.xsl'))
  transform = etree.XSLT(xslt_root)
else:
  # add amazon ec2 support here
  """
  with open(os.path.join(paliXmlUrlPrefix, 'cscd/tipitaka-latn.xsl'), 'r') as f:
    xslt_root = etree.fromstring(f.read())
  transform = etree.XSLT(xslt_root)
  """
  raise Exception('currently only Google App Engine is supported')


def getCanonXmlUrl(action):
  return os.path.join(paliXmlUrlPrefix, action)

def getTranslationXmlUrl(action, translationLocale, translator):
  xmlFilename = os.path.basename(action)
  code = getTranslatorSource(xmlFilename, translationLocale, translator)
  return os.path.join(trXmlUrlPrefix, '%s/%s/%s' % (
                                       translationLocale, code, xmlFilename))

def xslt(url):
  root = etree.parse(url)
  # transform xml with xslt
  return transform(root)


def paliXslt(action):
  return xslt(getCanonXmlUrl(action))


def translationXslt(action, translationLocale, translator):
  return xslt(getTranslationXmlUrl(action, translationLocale, translator))

@@ -308,16 +308,33 @@
 gine():%0A
+  import urllib2%0A
   if isP
@@ -352,16 +352,16 @@
 rver():%0A
-
     pali
@@ -894,31 +894,32 @@
 :%0A  
-xslt_root = etree.parse
+result = urllib2.urlopen
 (os.
@@ -929,19 +929,16 @@
 h.join(%0A
-   
         
@@ -987,16 +987,50 @@
 .xsl'))%0A
+  xslt_root = etree.parse(result)%0A
   transf
@@ -1745,30 +1745,206 @@
 :%0A  
-root = etree.parse(url
+if isGoogleAppEngine():%0A    result = urllib2.urlopen(url)%0A    root = etree.parse(result)%0A  else:%0A    # add amazon ec2 support here%0A    raise Exception('currently only Google App Engine is supported'
 )%0A  

fix url fetching bug (GAE does not allow lxml directly fetch url)