# w.c.s. - web application for online forms
# Copyright (C) 2005-2013  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import os

import django.template.loaders.filesystem
from django.conf import settings

from .qommon.template import get_theme_directory
from .qommon.publisher import get_cfg, get_publisher

class TemplateLoader(django.template.loaders.filesystem.Loader):
    def get_template_sources(self, template_name, template_dirs=None):
        if not template_dirs:
            template_dirs = []

            # theme set by hobo
            theme = get_publisher().get_site_option('theme', 'variables')

            # templates from tenant directory
            if theme:
                template_dirs.append(os.path.join(get_publisher().app_dir,
                    'templates', 'variants', theme))
                template_dirs.append(os.path.join(get_publisher().app_dir,
                    'theme', 'templates', 'variants', theme))
            template_dirs.append(os.path.join(get_publisher().app_dir, 'templates'))
            template_dirs.append(os.path.join(get_publisher().app_dir, 'theme', 'templates'))

            current_theme = get_cfg('branding', {}).get('theme', 'default')
            theme_directory = get_theme_directory(current_theme)
            if theme_directory:
                # templates from theme directory
                theme_directory = os.path.join(theme_directory, 'templates')

                if theme:
                    # template theme set by hobo
                    template_dirs.append(os.path.join(theme_directory, 'variants', theme))

                template_dirs.append(theme_directory)

            template_dirs = tuple(template_dirs)

        return super(TemplateLoader, self).get_template_sources(template_name, template_dirs)
