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

from wcs.qommon import _
from wcs.qommon import get_cfg, get_logger
from wcs.qommon.form import Form, StringWidget, CheckboxWidget, SingleSelectWidget
from wcs.qommon.backoffice.menu import html_top
from quixote.html import htmltext

from .payments import Regie


# constants
ABELIUM_DOMINO = 'abelium_domino'
ACTIVATED = 'activated'
WSDL_URL = 'wsdl_url'
SERVICE_URL = 'service_url'
DOMAIN = 'domain'
LOGIN = 'login'
PASSWORD = 'password'
INVOICE_REGIE = 'invoice_regie'

try:
    import abelium_domino_ws
except ImportError, e:
    abelium_domino_ws = None
    import_error = e

def get_abelium_cfg(publisher):
    if not publisher:
        publisher = get_publisher()
    return publisher.cfg.get(ABELIUM_DOMINO, {})

def is_activated(publisher=None):
    cfg = get_abelium_cfg(publisher)
    return cfg.get(ACTIVATED, False) and abelium_domino_ws is not None

def get_client(publisher=None):
    publisher = publisher or get_publisher()

    cfg = get_abelium_cfg(publisher)
    try:
        publisher._ws_cache = abelium_domino_ws.DominoWs(
            url=cfg.get(WSDL_URL, ''),
            domain=cfg.get(DOMAIN,''),
            login=cfg.get(LOGIN, ''),
            password=cfg.get(PASSWORD, ''),
            location=cfg.get(SERVICE_URL),
            logger=get_logger())
    except IOError:
        return None
    return publisher._ws_cache

def get_family(user, publisher=None):
    family = None
    if user is None:
        return None
    client = get_client(publisher)
    if not client:
        return None
    if hasattr(user, 'abelium_domino_code_famille'):
        family = client.get_family_by_code_interne(
            user.abelium_domino_code_famille)
    if family is None and user.email:
        family = client.get_family_by_mail(user.email)
    return family

def get_invoice_regie(publisher=None):
    cfg = get_abelium_cfg(publisher)
    regie_id = cfg.get(INVOICE_REGIE)
    if not regie_id:
        return None
    return Regie.get(regie_id, ignore_errors=True)

class AbeliumDominoDirectory(Directory):
    _q_exports = [ '' , 'debug' ]
    label = N_('Domino')

    def debug(self):
        from abelium_domino_vars import SESSION_CACHE
        html_top(ABELIUM_DOMINO)
        r = TemplateIO(html=True)
        r += htmltext('<form method="post"><button>Lancer le cron</button></form>')
        if get_request().get_method() == 'POST':
            try:
                from abelium_domino_synchro import synchronize_domino
                synchronize_domino(get_publisher())
            except Exception, e:
                r += htmltext('<pre>%s</pre>') % repr(e)
        r += htmltext('<p>code interne: %s</p>') % getattr(get_request().user, str('abelium_domino_code_famille'), None)
        r += htmltext('<dl>')
        context = get_publisher().substitutions.get_context_variables()
        for var in sorted(context.keys()):
            value = context[var]
            if value:
                r += htmltext('<dt>%s</dt>') % var
                r += htmltext('<dd>%s</dt>') % value
        r += htmltext('</dl>')
        delattr(get_request().session, SESSION_CACHE)

    def _q_index(self):
        publisher = get_publisher()
        cfg = get_cfg(ABELIUM_DOMINO, {})
        form = self.form(cfg)

        title = _('Abelium Domino')
        html_top(ABELIUM_DOMINO, title = title)
        r = TemplateIO(html=True)
        r += htmltext('<h2>%s</h2>') % title

        if form.is_submitted() and not form.has_errors():
            if form.get_widget('cancel').parse():
                return redirect('..')
            if form.get_widget('submit').parse():
                for name in [f[0] for f in self.form_desc] + [INVOICE_REGIE]:
                    widget = form.get_widget(name)
                    if widget:
                        cfg[name] = widget.parse()
                publisher.cfg[ABELIUM_DOMINO] = cfg
                publisher.write_cfg()
                return redirect('.')

        if abelium_domino_ws:
            r += form.render()
        else:
            message = _('The Abelium Domino module is not '
                    'activated because of this error when '
                    'loading it: %r') % import_error
            r += htmltext('<p class="errornotice">%s</p>') % message
        r += htmltext('<dl style="display: none">')
        context = get_publisher().substitutions.get_context_variables()
        for var in sorted(context.keys()):
            value = context[var]
            if value:
                r += htmltext('<dt>%s</dt>') % var
                r += htmltext('<dd>%s</dt>') % value
        r += htmltext('</dl>')
        return r.getvalue()

    form_desc = (
            # name, required, title, kind
            (ACTIVATED, False, _('Activated'), bool),
            (WSDL_URL, True, _('WSDL URL'), str),
            (SERVICE_URL, False, _('Service URL'), str),
            (DOMAIN, True, _('Domain'), str),
            (LOGIN, True, _('Login'), str),
            (PASSWORD, True, _('Password'), str),
    )


    def form(self, initial_value={}):
        form = Form(enctype='multipart/form-data')
        kinds = { str: StringWidget, bool: CheckboxWidget }
        for name, required, title, kind in self.form_desc:
            widget = kinds[kind]
            form.add(widget, name, required=required, title=title,
                    value=initial_value.get(name, ''))
        options = [(regie.id, regie.label) \
                        for regie in Regie.values()]
        options.insert(0, (None, _('None')))
        form.add(SingleSelectWidget, INVOICE_REGIE,
                title=_('Regie which will receive payments'),
                value=initial_value.get(INVOICE_REGIE),
                options=options)

        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))

        return form
