"""
Cuchulufm is a series of wrappers for bottle, mako and others and construct a simple headless cms.

Copyright (C) 2025 Antonio de la Rosa Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.


You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

# Template frontend from mako. 

#import gettext
from mako.template import Template
from mako.lookup import TemplateLookup
from os import path
try:
    from settings import config
except:
    class config:
        theme='default'
        reloader=False

#import gettext
import sys
from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.urls import make_url, make_media_url, add_get_parameters, url_for
from cuchulu.libraries.db.formsutils import csrf_token
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.wsgiapp import app

"""
def _(text):
    
    return gettext.gettext(text)
"""

def env_theme(module, cache_enabled=True, cache_impl='', cache_args={}, module_directory="./tmp/modules"):
    """Function for create an environment for mako templates
    
    Function for create an environment for mako templates. Really is a shortcut for TemplateLookup mako function. You can define cache options and module_directory for templates compiled
    
    Args:
        module (str): The module where the templates can be founded
        cache_enabled (boolean): If True then mako template cache is enabled, is False, mako template cache is disabled.
        cache_args (dict): Cache Args dict parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
        module_directory (str): Module directory parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
    
    Returns:
    
        template (TemplateLookup): Return TemplateLookup object
    
    """

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

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

    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)

def get_file():
    
    return __file__

class PTemplate:
    """A class used how shortcuts for Mako template functions.
    """
    
    templates_loaded={}
    
    def __init__(self, environment):
        """A class used how shortcuts for Mako template functions.
        
        This class is used to have a set of shortcuts and hooks to Mako templates functions and methods over a series of default options. 
        
        Args: 
            environment (TemplateLookup): A TemplateLookup object generated with env_theme function
        
        Attributes:
            autoescape_ext (set): A set of extensions file where automatic autoescape is used
            environment (TemplateLookup): A TemplateLookup object generated with env_theme function
            filters (list): A list of functions used for add filters to your templates.
            js (list): A list of javascript sources for generate js html load tags.
            
        """
        
        self.autoescape_ext=('html', 'htm', 'xml', 'phtml', 'js')

        self.env=environment
        
        self.filters={}
        
        self.js={}
        
        self.url_for=url_for
        
        self.add_filter(I18n.lang)
        
        self.add_filter(make_url)
        
        self.add_filter(make_media_url)
        """
        if not url_for_function:
            
            url_for=url_for_bottle
            
            self.add_filter(url_for)
            
        else:
            
            url_for=url_for_function
            
            self.add_filter(url_for)
            
        """
        self.add_filter(self.url_for)
        
        self.add_filter(csrf_token)
        
        self.add_filter(add_get_parameters)
        
        self.add_filter(self.add_js)
        
        self.add_filter(self.load_js)
        
        self.add_filter(show_flash_message)
        
        self.add_filter(get_file)
        
        # Loading language domain for gettext in templates
        
        base_name=path.dirname(path.realpath(__file__))
        
        module_env=self.env.directories[1].replace('/templates', '')
        
        #print(path.basename(module_env)+' '+base_name+'/languages/')
        
        self.l=PGetText(module_env+'/app.py')
        
        self.i18n=I18n(module_env)

        self.add_filter(self._)
        
        self.i18n=I18n(base_name)
        
        self.add_filter(self.i18n.slang)
        
        self.add_filter(self.i18n.tlang)

    def _(self, text):
    
        return self.l.gettext(text)

    def add_js(self, js, module=''):
        """Function for add js to self.js attribute
        
        Add a js file name to an attribute list called self.js with the <script> tag to add it to the header of an html code 
        
        Args:
            js (str): The name of js file. Normally you save the file in media/js folder in module or theme
            module (str): Optional. Where is saved the js file. 
            
        Returns:
            dummy (str): Dummy return necessary because mako expect return something
        """
        if not js in self.js:
            self.js[js]='<script language="Javascript" src="{}"></script>'.format(make_media_url('js/'+js, module))
            
        return ""
        
    def load_js(self):
        
        return "\n".join(self.js.values())
        

    """
    def gettext(self, text):
        return gettext.dgettext(self.domain_gettext, text)
    """
        
    def load_template(self, template_file, **arguments):
        """Load a mako template and return the result
        
        Load a mako template and return the results with different arguments applied
        
        Args: 
            template_file (str): The name of template file. The template is searched using configuration defined in self.env
            **arguments (mixed): Extra arguments with variables passed to template
            
        Returns:
            template (str): Return a template rendered using mako class from self.env
        """
        
        """
        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):
        """Simple helper method for get an extension from filename
        
        Args:
            template_name (str): The 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):
        """Experimental method for parse a template
        
        Experimental method for parse a template, similar to load_template but try cache the template loaded
        
        Args:
            template_file (str): The name of template file. The template is searched using configuration defined in self.env
            **arguments (mixed): Extra arguments with variables passed to template
            
        Returns:
            dummy (str): Dummy return necessary because mako expect return something
        """
        
        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):
        """Method for add filters to self.filters attributes
        
        Method for add filters to self.filters attributes for use in templates
        
        Args:
            filter_name (function): Filter function
        """

        self.filters[filter_name.__name__]=filter_name

def set_flash_message(message):
    
    s=get_session()
    
    s['flash']=message
    
    s.save()

def show_flash_message():
    
    s=get_session()
    
    message=s.get('flash', '')
    
    if message!='':
        s['flash']=''
    
    return message

def add_css_home_local(file_css, module):
    
    pass

env=env_theme(__file__)

standard_t=PTemplate(env)

