# w.c.s. - web application for online forms
# Copyright (C) 2005-2010  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/>.

from quixote import redirect
from quixote.directory import Directory, AccessControlled
from quixote.html import TemplateIO, htmltext

from .. import _
from ..form import *
from ..admin.cfg import cfg_submit
from ..backoffice.menu import html_top

class SettingsDirectory(AccessControlled, Directory):
    def _q_access(self):
        get_response().breadcrumb.append( ('settings/', _('Settings')) )

    def schema_to_form(self, schema):
        form = Form(enctype='multipart/form-data')
        cfg = get_cfg(schema['name'], {})
        for option_name in schema['options']:
            option = schema['options'][option_name]
            if option['type'] == 'boolean':
                form.add(CheckboxWidget, option_name, title = _(option.get('title')),
                         value = cfg.get(option_name, option.get('default', False)))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        return form

    def config_page_from_schema(self, schema):
        title = _(schema['title'])
        name = schema['name']
        form = self.schema_to_form(schema)
        if form.get_widget('cancel').parse():
            return redirect('.')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = title)
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % title
            r += form.render()
            return r.getvalue()
        else:
            cfg_submit(form, name, schema['options'].keys())
            return redirect('')

    session_cfg_schema = {
            'name': 'session',
            'title': N_('Session'),
            'options': {
                'ip_linked': { 'type': 'boolean',
                               'default': False,
                               'title': N_('Fix sessions to an IP address')},
                },
            }

    def session(self):
        get_response().breadcrumb.append(('session', _('Session')))
        return self.config_page_from_schema(self.session_cfg_schema)

    def language(self):
        form = Form(enctype='multipart/form-data')
        language_cfg = get_cfg('language', {})

        form.add(SingleSelectWidget, 'language', title = _('Language'),
                value = language_cfg.get('language'),
                options = [(None, _('System Default')),
                           ('HTTP', _('From HTTP Accept-Language header')),
                           ('en', _('English')),
                           ('fr', _('French')),
                           ('de', _('German')),
                          ])

        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('language', _('Language')))
            html_top('settings', title = _('Language'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Language')
            r += form.render()
            return r.getvalue()
        else:
            cfg_submit(form, 'language', ['language'])
            return redirect('.')

    def debug_options(self):
        form = Form(enctype="multipart/form-data")
        debug_cfg = get_cfg('debug', {})
        form.add(StringWidget, 'error_email', title = _('Email for Tracebacks'),
                value = debug_cfg.get('error_email', ''))
        form.add(SingleSelectWidget, 'display_exceptions', title = _('Display Exceptions'),
                value = debug_cfg.get('display_exceptions', ''),
                options = [ (str(''), _('No display')),
                            (str('text'), _('Display as Text')),
                            (str('text-in-html'), _('Display as Text in an HTML error page')),
                            (str('html'), _('Display as HTML')) ])
        form.add(CheckboxWidget, 'logger', title=_('Logger'),
                value=debug_cfg.get('logger', True))
        form.add(CheckboxWidget, 'debug_mode', title = _('Enable debug mode'),
                value = debug_cfg.get('debug_mode', False))
        form.add(StringWidget, 'mail_redirection', title = _('Mail redirection'),
                value = debug_cfg.get('mail_redirection', ''),
                hint=_('If set, send all emails to that address instead of the real recipients'))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))

        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('debug_options', _('Debug Options')))
            html_top('settings', title = _('Debug Options'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Debug Options')
            r += form.render()
            return r.getvalue()
        else:
            cfg_submit(form, 'debug', ('error_email', 'display_exceptions',
                                       'logger', 'debug_mode',
                                       'mail_redirection'))
            return redirect('.')
