##
## browser.py
## Login : <uli@pu.smp.net>
## Started on  Sun Jun 27 11:03:10 2010 Uli Fouquet
## $Id$
## 
## Copyright (C) 2010 Uli Fouquet
## 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, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
"""UI components for JAMB tables.
"""
import grok

from waeup.sirp.browser import (
    WAeUPPage, WAeUPEditFormPage, WAeUPAddFormPage,
    WAeUPDisplayFormPage, NullValidator)
from waeup.sirp.interfaces import IWAeUPObject
from waeup.sirp.jambtables import JAMBDataTable
from waeup.sirp.jambtables.util import get_applicant_data
from waeup.sirp.jambtables.interfaces import IApplicant, IApplicantContainer

#from zope.formlib.objectwidget import ObjectWidget
from zope.formlib.sequencewidget import ListSequenceWidget, SequenceDisplayWidget
from zope.formlib.widget import CustomWidgetFactory
from waeup.sirp.jambtables.applicants import ResultEntry
from waeup.sirp.widgets.objectwidget import (
    WAeUPObjectWidget, WAeUPObjectDisplayWidget)
from waeup.sirp.widgets.multilistwidget import (
    MultiListWidget, MultiListDisplayWidget)

results_widget = CustomWidgetFactory(
    WAeUPObjectWidget, ResultEntry)

results_display_widget = CustomWidgetFactory(
    WAeUPObjectDisplayWidget, ResultEntry)

#list_results_widget = CustomWidgetFactory(
#    ListSequenceWidget, subwidget=results_widget)

list_results_widget = CustomWidgetFactory(
    MultiListWidget, subwidget=results_widget)

list_results_display_widget = CustomWidgetFactory(
    MultiListDisplayWidget, subwidget=results_display_widget)

class ApplicationsPage(WAeUPPage):
    grok.context(IApplicantContainer)
    grok.name('index')
    title = 'Applications'
    pnav = 1
    
    def getApplications(self):
        """Get a list of all stored applications.
        """
        for key, val in self.context.items():
            url = self.url(val)
            yield(dict(url=url, name=key))

class AddApplicant(WAeUPAddFormPage):
    grok.context(IApplicantContainer)
    grok.name('add')
    form_fields = grok.AutoFields(IApplicant)
    form_fields['fst_sit_results'].custom_widget = list_results_widget
    label = 'Add Applicant'
    title = 'Add Applicant'
    pnav = 1

    @grok.action('Add applicant')
    def addApplicant(self, **data):
        from waeup.sirp.jambtables.applicants import Applicant
        applicant = Applicant()
        self.applyData(applicant, **data)
        self.context[applicant.reg_no] = applicant
        self.redirect(self.url(self.context))

class DisplayApplicant(WAeUPDisplayFormPage):
    grok.context(IApplicant)
    grok.name('index')
    form_fields = grok.AutoFields(IApplicant)
    form_fields['fst_sit_results'].custom_widget = list_results_display_widget
    label = 'Applicant'
    title = 'Applicant'
    pnav = 1

class EditApplicant(WAeUPEditFormPage):
    grok.context(IApplicant)
    grok.name('edit')
    form_fields = grok.AutoFields(IApplicant)
    form_fields['fst_sit_results'].custom_widget = list_results_widget
    label = 'Edit Application'
    title = 'Edit Application'
    pnav = 1

    @grok.action('Save')
    def save(self, **data):
        print "DATA: ", data
        self.applyData(self.context, **data)
        print "ENTRY: ", self.context.fst_sit_results
        self.context._p_changed = True
        return

    @grok.action('Save and return')
    def saveAndReturn(self, **data):
        self.applyData(self.context, **data)
        self.redirect(self.url(self.context))
        return

    @grok.action('Cancel', validator=NullValidator)
    def cancel(self, **data):
        self.redirect(self.url(self.context))
        return

class Login_PDE(WAeUPPage):
    grok.context(IWAeUPObject)
    grok.name('login_pde')

    title = 'PDE Login'
    pnav = 1

    def update(self, reg_no=None, ac_series=None, ac_number=None):
        """Validate credentials and redirect or show error.

        XXX: log things happening here
        XXX: consider real login procedure with single applicant user.
        """
        self.reg_no = reg_no
        self.ac_series = ac_series
        self.ac_number = ac_number
        for param in [reg_no, ac_series, ac_number]:
            if param is None:
                return
        ac = "PUDE-%s-%s" % (ac_series, ac_number)
        data = self.getApplicantData(reg_no, ac)
        if data is None:
            self.flash('Invalid data entered')
            return
        applicant_data, access_code = data
        app_page = self.url(applicant_data, '@@edit')
        # XXX: Invalidate ACCESS_CODE
        self.redirect(app_page)
        return

    def getCurrentSession(self):
        """Get the current session.

        XXX: This should be computed or retrieved from elsewhere.
        """
        return u'2010/2011'

    def getDeadline(self):
        """Get application submission deadline.

        XXX: This should be computed or retrieved from elsewhere.
        """
        return u"""Application submission deadline is at Midnight on Friday,
                   01. October 2010. No application will be treated
                   after the deadline."""

    def getApplicantData(self, reg_no, ac):
        """Validate credentials and return applicant data.

        Returns tuple ``(<APPLICANT_ENTRY>, <ACCESSCODE>) on
        successful validation and ``None`` else.

        We expect a JAMB registration number and an access code in
        format ``PUDE-XXX-XXXXXXXXXX``.

        See
        :func:`waeup.sirp.jambtables.util.get_applicant_data`
        for details.
        """
        return get_applicant_data(reg_no, ac)
