## $Id: browser.py 9281 2012-10-03 07:08:02Z henrik $
##
## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
## 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
##
import grok
from zope.i18n import translate
from zope.schema.interfaces import ConstraintNotSatisfied
from hurry.workflow.interfaces import IWorkflowInfo
from waeup.kofa.interfaces import REQUESTED
from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
from waeup.kofa.browser.layout import KofaEditFormPage
from waeup.kofa.browser.viewlets import ManageActionButton
from waeup.kofa.browser.layout import action, jsaction
from waeup.kofa.students.browser import (
    StudentClearPage, StudentRejectClearancePage,
    StudyCourseDisplayFormPage,
    StudyLevelEditFormPage,
    msave, emit_lock_message)
from waeup.kofa.students.workflow import FORBIDDEN_POSTGRAD_TRANS
from kofacustom.nigeria.students.browser import (
    NigeriaOnlinePaymentDisplayFormPage,
    NigeriaStudentBaseManageFormPage,
    NigeriaOnlinePaymentAddFormPage,
    NigeriaExportPDFPaymentSlipPage,
    )
#from waeup.uniben.students.interfaces import ICustomStudent

from waeup.uniben.students.interfaces import (
    ICustomStudentOnlinePayment, ICustomStudentStudyCourse)
from waeup.uniben.interfaces import MessageFactory as _

class CustomStudentBaseManageFormPage(NigeriaStudentBaseManageFormPage):
    """ View to manage student base data
    """
    #grok.context(ICustomStudent)

    def getTransitions(self):
        """Return a list of dicts of allowed transition ids and titles.

        Each list entry provides keys ``name`` and ``title`` for
        internal name and (human readable) title of a single
        transition.
        """
        allowed_transitions = [t for t in self.wf_info.getManualTransitions()
            if not t[0].startswith('pay')]
        if self.context.is_postgrad and not self.context.is_special_postgrad:
            allowed_transitions = [t for t in allowed_transitions
                if not t[0] in FORBIDDEN_POSTGRAD_TRANS]
        return [dict(name='', title=_('No transition'))] +[
            dict(name=x, title=y) for x, y in allowed_transitions]

class CustomOnlinePaymentDisplayFormPage(NigeriaOnlinePaymentDisplayFormPage):
    """ Page to view an online payment ticket
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment)
    form_fields[
        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields[
        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomOnlinePaymentAddFormPage(NigeriaOnlinePaymentAddFormPage):
    """ Page to add an online payment ticket
    """
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).select(
        'p_category')

class CustomExportPDFPaymentSlipPage(NigeriaExportPDFPaymentSlipPage):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment)
    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')


## In case we need to deactivate clearance
#class CustomStudentClearPage(StudentClearPage):
#    """ Clear student by clearance officer
#    """
#    def update(self):
#        self.flash('Clearance temporarily disabled!')
#        self.redirect(self.url(self.context,'view_clearance'))
#        return

#class CustomStudentRejectClearancePage(StudentRejectClearancePage):
#    """ Reject clearance by clearance officers
#    """

#    def update(self):
#        self.flash('Clearance temporarily disabled!')
#        self.redirect(self.url(self.context,'view_clearance'))
#        return

class StudyCourseEditActionButton(ManageActionButton):
    grok.order(1)
    grok.context(ICustomStudentStudyCourse)
    grok.view(StudyCourseDisplayFormPage)
    grok.require('waeup.clearStudent')
    text = _('Edit level')
    target = 'edit_level'

    @property
    def target_url(self):
        if self.context.is_current and self.context.student.state == REQUESTED:
            return self.view.url(self.view.context, self.target)
        return False

class StudyCourseCOEditFormPage(KofaEditFormPage):
    """ Page to edit the student study course data by clearance officers.

    This form page is available only in Uniben.
    """
    grok.context(ICustomStudentStudyCourse)
    grok.name('edit_level')
    grok.require('waeup.clearStudent')
    label = _('Edit current level')
    pnav = 4
    form_fields = grok.AutoFields(
        ICustomStudentStudyCourse).select('current_level')

    def update(self):
        if not (self.context.is_current and
            self.context.student.state == REQUESTED):
            emit_lock_message(self)
            return
        super(StudyCourseCOEditFormPage, self).update()
        return

    @action(_('Save'), style='primary')
    def save(self, **data):
        try:
            msave(self, **data)
        except ConstraintNotSatisfied:
            # The selected level might not exist in certificate
            self.flash(_('Current level not available for certificate.'))
            return
        #notify(grok.ObjectModifiedEvent(self.context.__parent__))
        return

class CustomStudyLevelEditFormPage(StudyLevelEditFormPage):
    """ Page to edit the student study level data by students.

    """

    def _registerCourses(self, **data):
        """ This customized version does allow 'special postgraduate'
        students to register their courses.
        """
        if self.context.student.is_postgrad and \
            not self.context.student.is_special_postgrad:
            self.flash(_(
                "You are a postgraduate student, "
                "your course list can't bee registered."))
            self.redirect(self.url(self.context))
            return
        if self.total_credits > self.max_credits:
            self.flash(_('Maximum credits of ${a} exceeded.',
                mapping = {'a':self.max_credits}))
            return
        IWorkflowInfo(self.context.student).fireTransition(
            'register_courses')
        self.flash(_('Course list has been registered.'))
        self.redirect(self.url(self.context))
        return