import os

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

import wcs.admin.root
import wcs.root
from wcs.roles import get_user_roles

from wcs.qommon import _
from wcs.qommon import errors, get_cfg
from wcs.qommon.form import *

import wcs.admin.settings
from wcs.formdef import FormDef
from wcs.categories import Category
from wcs.qommon.backoffice.menu import html_top

from .events import get_default_event_tags
import re
from .abelium_domino_ui import AbeliumDominoDirectory


class PanelDirectory(Directory):
    _q_exports = ['', 'update', 'announces', 'permissions', 'event_keywords',
            'announce_themes', 'strongbox', 'clicrdv', 'domino']
    label = N_('Control Panel')

    domino = AbeliumDominoDirectory()

    def _verify_mask(self, form):
        if form.is_submitted():
            if not re.match("[0-9Xx]*$", form.get('mobile_mask') or ''):
                form.set_error('mobile_mask', _('Invalid value'))
            else:
                string_value = form.get_widget('mobile_mask').value
                if string_value:
                    form.get_widget('mobile_mask').value = string_value.upper()

    def announces(self):
        announces_cfg = get_cfg('announces', {})
        sms_cfg = get_cfg('sms', {})
        form = Form(enctype='multipart/form-data')
        hint = ""
        if sms_cfg.get('mode','') in ("none",""):
            hint = htmltext(_('You must also <a href="%s">configure your SMS provider</a>') % "../settings/sms")

        form.add(CheckboxWidget, 'sms_support', title = _('SMS support'),
                hint = hint, value = announces_cfg.get('sms_support', 0))
        form.add(StringWidget, 'mobile_mask', title = _('Mask for mobile numbers'),
                hint = _('example: 06XXXXXXXX'),
                value = announces_cfg.get('mobile_mask',''))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))

        self._verify_mask(form)

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

        if not form.is_submitted() or form.has_errors():
            get_response().breadcrumb.append(('aq/announces', _('Announces Options')))
            html_top('settings', _('Announces Options'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Announces Options')
            r += form.render()
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'announces', ('sms_support','mobile_mask'))
            return redirect('..')

    def permissions(self):
        permissions_cfg = get_cfg('aq-permissions', {})
        form = Form(enctype='multipart/form-data')
        form.add(SingleSelectWidget, 'forms', title = _('Admin role for forms'),
                value = permissions_cfg.get('forms', None),
                options = [(None, _('Nobody'), None)] + get_user_roles())
        if get_publisher().has_site_option('auquotidien-events'):
            form.add(SingleSelectWidget, 'events', title = _('Admin role for events'),
                    value = permissions_cfg.get('events', None),
                    options = [(None, _('Nobody'), None)] + get_user_roles())
        if get_publisher().has_site_option('auquotidien-links'):
            form.add(SingleSelectWidget, 'links', title = _('Admin role for links'),
                    value = permissions_cfg.get('links', None),
                    options = [(None, _('Nobody'), None)] + get_user_roles())
        if get_publisher().has_site_option('auquotidien-announces'):
            form.add(SingleSelectWidget, 'announces', title = _('Admin role for announces'),
                    value = permissions_cfg.get('announces', None),
                    options = [(None, _('Nobody'), None)] + get_user_roles())
        if get_publisher().has_site_option('auquotidien-payments'):
            form.add(SingleSelectWidget, 'payments', title = _('Admin role for payments'),
                    value = permissions_cfg.get('payments', None),
                    options = [(None, _('Nobody'), None)] + get_user_roles())
        if get_publisher().has_site_option('auquotidien-strongbox'):
            form.add(SingleSelectWidget, 'strongbox', title = _('Admin role for strongbox'),
                    value = permissions_cfg.get('strongbox', None),
                    options = [(None, _('Nobody'), None)] + get_user_roles())
        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(('aq/permissions', _('Permissions')))
            html_top('settings', _('Permissions'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Permissions')
            r += form.render()
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'aq-permissions',
                        ('forms', 'events', 'links', 'announces', 'payments', 'strongbox'))
            return redirect('..')

    def event_keywords(self):
        misc_cfg = get_cfg('misc', {})
        form = Form(enctype='multipart/form-data')
        form.add(WidgetList, 'event_tags', title = _('Event Keywords'),
                value = misc_cfg.get('event_tags', get_default_event_tags()),
                elemnt_type = StringWidget,
                add_element_label = _('Add Keyword'),
                element_kwargs = {str('render_br'): False, str('size'): 30})

        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(('aq/event_keywords', _('Event Keywords')))
            html_top('settings', _('Event Keywords'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Event Keywords')
            r += form.render()
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'misc', ('event_tags',))
            return redirect('..')

    def announce_themes(self):
        misc_cfg = get_cfg('misc', {})
        form = Form(enctype='multipart/form-data')
        form.add(WidgetList, 'announce_themes', title = _('Announce Themes'),
                value = misc_cfg.get('announce_themes', []),
                elemnt_type = StringWidget,
                add_element_label = _('Add Theme'),
                element_kwargs = {str('render_br'): False, str('size'): 30})

        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(('aq/announce_themes', _('Announce Themes')))
            html_top('settings', _('Announce Themes'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Announce Themes')
            r += form.render()
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'misc', ('announce_themes',))
            return redirect('..')

    def strongbox(self):
        if not get_publisher().has_site_option('strongbox'):
            raise errors.TraversalError()
        misc_cfg = get_cfg('misc', {})
        form = Form(enctype='multipart/form-data')
        form.add(CheckboxWidget, 'aq-strongbox', title=_('Strongbox Support'),
                value=misc_cfg.get('aq-strongbox'), required=False)

        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(('aq/strongbox', _('Strongbox Support')))
            html_top('settings', _('Strongbox Support'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('Strongbox Support')
            r += form.render()
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'misc', ('aq-strongbox',))
            return redirect('..')

    def clicrdv(self):
        if not get_publisher().has_site_option('clicrdv'):
            raise errors.TraversalError()
        misc_cfg = get_cfg('misc', {})
        form = Form(enctype='multipart/form-data')
        form.add(SingleSelectWidget, 'aq-clicrdv-server', title=_('ClicRDV Server'),
                value=misc_cfg.get('aq-clicrdv-server', 'sandbox.clicrdv.com'), required=True,
                options=[(str('www.clicrdv.com'), _('Production Server')),
                         (str('sandbox.clicrdv.com'), _('Sandbox Server'))])
        form.add(StringWidget, 'aq-clicrdv-api-key', title=_('API Key'),
                value=misc_cfg.get('aq-clicrdv-api-key'), required=False,
                size=40, hint=_('Empty to disable ClicRDV support'))
        form.add(StringWidget, 'aq-clicrdv-api-username', title=_('Username'),
                value=misc_cfg.get('aq-clicrdv-api-username'), required=False)
        form.add(StringWidget, 'aq-clicrdv-api-password', title=_('Password'),
                value=misc_cfg.get('aq-clicrdv-api-password'), required=False)

        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(('aq/clicrdv', _('ClicRDV Integration')))
            html_top('settings', _('ClicRDV Integration'))
            r = TemplateIO(html=True)
            r += htmltext('<h2>%s</h2>') % _('ClicRDV Integration')
            r += form.render()
            r += htmltext('<p>%s</p>') % _('Available Interventions: ')
            try:
                from clicrdv import get_all_intervention_sets
                intervention_sets = get_all_intervention_sets()
                r += htmltext('<ul>')
                for s in intervention_sets:
                    r += htmltext('<li><strong>clicrdv_get_interventions_in_set(%s)</strong> - %s') % (
                            s['id'], s['name'])
                    r += htmltext('<ul>')
                    for n, intervention in s['interventions']:
                        r += htmltext('<li>%s (id: %s)</li>') % (intervention, n)
                    r += htmltext('</ul></li>')
                r += htmltext('</ul>')
            except Exception, e:
                r += htmltext('<p>%s (%s)</p>') % (
                        _('Cannot access to ClicRDV service'), str(e))
            return r.getvalue()
        else:
            from wcs.admin.settings import cfg_submit
            cfg_submit(form, 'misc', ('aq-clicrdv-server',
                                      'aq-clicrdv-api-key',
                                      'aq-clicrdv-api-username',
                                      'aq-clicrdv-api-password'))
            return redirect('..')


class SettingsDirectory(wcs.admin.settings.SettingsDirectory):
    def _q_index(self):
        if not (get_publisher().has_site_option('auquotidien-announces') or
                get_publisher().has_site_option('auquotidien-links') or
                get_publisher().has_site_option('auquotidien-events') or
                get_publisher().has_site_option('auquotidien-payments') or
                get_publisher().has_site_option('auquotidien-strongvox')):
            return super(SettingsDirectory, self)._q_index()
        r = TemplateIO(html=True)
        r += htmltext(super(SettingsDirectory, self)._q_index())
        r += htmltext('<div class="splitcontent-right">')
        r += htmltext('<div class="bo-block">')
        r += htmltext('<h2>%s</h2>') % _('Extra Options')
        r += htmltext('<ul>')
        if get_publisher().has_site_option('auquotidien-announces'):
            r += htmltext('<li><a href="aq/announces">%s</a></li>') % _('Announces Options')
        r += htmltext('<li><a href="aq/permissions">%s</a></li>') % _('Permissions')
        if get_publisher().has_site_option('auquotidien-events'):
            r += htmltext('<li><a href="aq/event_keywords">%s</a></li>') % _('Event Keywords')
        if get_publisher().has_site_option('auquotidien-announces'):
            r += htmltext('<li><a href="aq/announce_themes">%s</a></li>') % _('Announce Themes')
        if get_publisher().has_site_option('strongbox'):
            r += htmltext('<li><a href="aq/strongbox">%s</a></li>') % _('Strongbox Support')
        if get_publisher().has_site_option('clicrdv'):
            r += htmltext('<li><a href="aq/clicrdv">%s</a></li>') % _('ClicRDV Integration')
        if get_publisher().has_site_option('domino'):
            r += htmltext('<li><a href="aq/domino">%s</a></li>') % _('Abelium Domino Integration')
        r += htmltext('</ul>')
        r += htmltext('</div>')
        r += htmltext('</div>')
        return r.getvalue()

    def _q_lookup(self, component):
        if component == 'aq':
            return PanelDirectory()
        return super(SettingsDirectory, self)._q_lookup(component)

from . import categories_admin
