# Template frontend from mako. 

from mako.template import Template
from flask import session, url_for
from mako.lookup import TemplateLookup
from os import path
from settings import config
import gettext
import sys
from paramecio2.libraries.i18n import I18n
from paramecio2.libraries.urls import make_url, make_media_url, add_get_parameters
from paramecio2.libraries.formsutils import csrf_token

def env_theme(module, cache_enabled=True, cache_impl='', cache_args={}, module_directory="./tmp/modules"):

    ext=module[len(module)-3:]
        
    if ext=='.py':
    
        module=path.dirname(module)

    standard_templates=path.dirname(__file__)+'/templates'

    module_directory+='/'+module

    module_templates=module+'/templates'
    
    theme_templates='themes/'+config.theme+'/templates'
    
    search_folders=[theme_templates, module_templates, standard_templates]
    
    #if self.inject_folder is not None:
        #search_folders.insert(1, self.inject_folder+'/templates')
    
    #Standard templates
    #print(standard_templates)
    return TemplateLookup(directories=search_folders, default_filters=['h'], input_encoding='utf-8', encoding_errors='replace', cache_enabled=cache_enabled, cache_impl=cache_impl, cache_args=cache_args, module_directory=module_directory, filesystem_checks=config.reloader)

class PTemplate:
    
    templates_loaded={}
    
    def __init__(self, environment, prepare_gettext=True):
        
        self.autoescape_ext=('html', 'htm', 'xml', 'phtml', 'js')

        self.env=environment
        
        self.filters={}
        
        self.add_filter(I18n.lang)
        
        #self.add_filter(make_url)
        
        self.add_filter(make_media_url)
        
        self.add_filter(url_for)

        self.add_filter(csrf_token)
        
        self.add_filter(add_get_parameters)

    """
    def gettext(self, text):
        return gettext.dgettext(self.domain_gettext, text)
    """
        
    def load_template(self, template_file, **arguments):
        """
        if self.prepare_gettext:

            module_lang_dir=self.env.directories[1].replace('/templates', '/locales')

            module_name=path.basename(module_lang_dir.replace('/locales', ''))

            en = gettext.translation(module_name, localedir=module_lang_dir, languages=['en'])
            en.install()
            _=en.gettext            
            
            arguments.update({'_': _})
        """
        template = self.env.get_template(template_file)

        arguments.update(self.filters)
        
        return template.render(**arguments)        

    def guess_autoescape(self, template_name):
        
        if template_name is None or '.' not in template_name:
            return False
        
        ext = template_name.rsplit('.', 1)[1]

        return ext in self.autoescape_ext
    
    def render_template(self, template_file, **arguments):
        
        if not str(self.env.directories)+'/'+template_file in PTemplate.templates_loaded:
            PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file]=self.env.get_template(template_file)
        
        arguments.update(self.filters)
        
        return PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file].render(**arguments)

    def add_filter(self, filter_name):

        self.filters[filter_name.__name__]=filter_name

env=env_theme(__file__)

standard_t=PTemplate(env)

