## $Id: browser.py 15319 2019-02-04 10:05:45Z henrik $
##
## Copyright (C) 2011 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
##
"""UI components for basic applicants and related components.
"""
import grok
from time import time
from zope.formlib.textwidgets import BytesDisplayWidget
from zope.component import getUtility, createObject
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.applicants.browser import (
    ApplicantRegistrationPage, ApplicantsContainerPage,
    ExportPDFPageApplicationSlip,
    ExportJobContainerOverview,
    ExportJobContainerJobStart,
    ExportJobContainerDownload)
from waeup.kofa.browser.layout import action, UtilityView
from kofacustom.nigeria.applicants.browser import (
    NigeriaApplicantDisplayFormPage,
    NigeriaPDFApplicationSlip,
    NigeriaApplicantManageFormPage,
    NigeriaApplicantEditFormPage,
    )
from kofacustom.nigeria.applicants.interfaces import (
    UG_OMIT_DISPLAY_FIELDS,
    UG_OMIT_PDF_FIELDS,
    UG_OMIT_MANAGE_FIELDS,
    UG_OMIT_EDIT_FIELDS,
    PG_OMIT_DISPLAY_FIELDS,
    PG_OMIT_PDF_FIELDS,
    PG_OMIT_MANAGE_FIELDS,
    PG_OMIT_EDIT_FIELDS,
    )
from waeup.kofa.applicants.workflow import (
    ADMITTED, PAID, STARTED, NOT_ADMITTED, CREATED)
from kofacustom.edopoly.applicants.interfaces import (
    ICustomUGApplicantEdit, ICustomUGApplicant,
    ICustomPGApplicantEdit, ICustomPGApplicant,
    ICustomApplicant, ICustomSpecialApplicant,)

from kofacustom.edopoly.interfaces import MessageFactory as _

# Fields to be omitted in all display forms. course_admitted is
# rendered separately.

OMIT_DISPLAY_FIELDS = ('locked', 'course_admitted',
    'result_uploaded', 'suspended', 'special_application',
    'bank_account_number',
    'bank_account_name',
    'bank_name')

# UG students are all undergraduate students.
UG_OMIT_DISPLAY_FIELDS = OMIT_DISPLAY_FIELDS + (
    #'jamb_subjects',
    'programme_type',)
UG_OMIT_PDF_FIELDS = UG_OMIT_DISPLAY_FIELDS + ('phone',)
UG_OMIT_MANAGE_FIELDS = (
    'special_application',
    #'jamb_subjects',
    'programme_type')
UG_OMIT_EDIT_FIELDS = UG_OMIT_MANAGE_FIELDS + UG_OMIT_DISPLAY_FIELDS + (
    'student_id',
    'notice',
    'screening_score',
    'screening_venue',
    'screening_date',
    'aggregate')

class CustomApplicantDisplayFormPage(NigeriaApplicantDisplayFormPage):
    """A display view for applicant data.
    """
    grok.template('applicantdisplaypage')

    @property
    def form_fields(self):
        target = getattr(self.context.__parent__, 'prefix', None)
        if self.context.special:
            return grok.AutoFields(ICustomSpecialApplicant)
        form_fields = grok.AutoFields(ICustomUGApplicant)
        for field in UG_OMIT_DISPLAY_FIELDS:
            form_fields = form_fields.omit(field)
        form_fields['notice'].custom_widget = BytesDisplayWidget
        #form_fields['jamb_subjects'].custom_widget = BytesDisplayWidget
        if not getattr(self.context, 'student_id'):
            form_fields = form_fields.omit('student_id')
        if not getattr(self.context, 'screening_score'):
            form_fields = form_fields.omit('screening_score')
        if not getattr(self.context, 'screening_venue'):
            form_fields = form_fields.omit('screening_venue')
        if not getattr(self.context, 'screening_date'):
            form_fields = form_fields.omit('screening_date')
        if not self.context.admchecking_fee_paid():
            form_fields = form_fields.omit(
                'screening_score', 'aggregate', 'student_id')
        return form_fields

    @property
    def admission_checking_info(self):
        if self.context.state in (ADMITTED, NOT_ADMITTED, CREATED) and \
            not self.context.admchecking_fee_paid():
            return _('You must pay the admission checking fee '
                     'to view your screening results and your course admitted.')

    @property
    def display_actions(self):
        state = IWorkflowState(self.context).getState()
        actions = []
        if state in (ADMITTED, NOT_ADMITTED, CREATED) \
            and not self.context.admchecking_fee_paid():
            actions = [_('Add admission checking payment ticket')]
        return actions

    def getCourseAdmitted(self):
        """Return link, title and code in html format to the certificate
           admitted.
        """
        if self.admission_checking_info:
            return '<span class="hint">%s</span>' % self.admission_checking_info
        return super(CustomApplicantDisplayFormPage, self).getCourseAdmitted()

    @action(_('Add admission checking payment ticket'), style='primary')
    def addPaymentTicket(self, **data):
        self.redirect(self.url(self.context, '@@addacp'))
        return

class AdmissionCheckingFeePaymentAddPage(UtilityView, grok.View):
    """ Page to add an admission checking online payment ticket.
    """
    grok.context(ICustomApplicant)
    grok.name('addacp')
    grok.require('waeup.payApplicant')
    factory = u'waeup.ApplicantOnlinePayment'

    def _setPaymentDetails(self, payment):
        container = self.context.__parent__
        timestamp = ("%d" % int(time()*10000))[1:]
        session = str(container.year)
        try:
            session_config = grok.getSite()['configuration'][session]
        except KeyError:
            return _(u'Session configuration object is not available.'), None
        payment.p_id = "p%s" % timestamp
        payment.p_item = container.title
        payment.p_session = container.year
        payment.amount_auth = 0.0
        payment.p_category = 'admission_checking'
        payment.amount_auth = session_config.admchecking_fee
        if payment.amount_auth in (0.0, None):
            return _('Amount could not be determined.'), None
        return

    def update(self):
        if self.context.admchecking_fee_paid():
              self.flash(
                  _('Admission checking payment has already been made.'),
                  type='warning')
              self.redirect(self.url(self.context))
              return
        payment = createObject(self.factory)
        failure = self._setPaymentDetails(payment)
        if failure is not None:
            self.flash(failure[0], type='danger')
            self.redirect(self.url(self.context))
            return
        self.context[payment.p_id] = payment
        self.flash(_('Payment ticket created.'))
        self.redirect(self.url(payment))
        return

    def render(self):
        return

class CustomExportPDFPageApplicationSlip(ExportPDFPageApplicationSlip):
    """Deliver a PDF slip of the context.
    """

    def update(self):
        super(CustomExportPDFPageApplicationSlip, self).update()
        if self.context.state in (ADMITTED, NOT_ADMITTED, CREATED) and \
            not self.context.admchecking_fee_paid():
            self.flash(
                _('Please pay admission checking fee before trying to download '
                  'the application slip.'), type='warning')
            return self.redirect(self.url(self.context))
        return

class CustomPDFApplicationSlip(NigeriaPDFApplicationSlip):

    @property
    def form_fields(self):
        target = getattr(self.context.__parent__, 'prefix', None)
        form_fields = grok.AutoFields(ICustomUGApplicant)
        for field in UG_OMIT_PDF_FIELDS:
            form_fields = form_fields.omit(field)
        if not getattr(self.context, 'student_id'):
            form_fields = form_fields.omit('student_id')
        if not getattr(self.context, 'screening_score'):
            form_fields = form_fields.omit('screening_score')
        if not getattr(self.context, 'screening_venue'):
            form_fields = form_fields.omit('screening_venue')
        if not getattr(self.context, 'screening_date'):
            form_fields = form_fields.omit('screening_date')
        return form_fields

class CustomApplicantManageFormPage(NigeriaApplicantManageFormPage):
    """A full edit view for applicant data.
    """

    @property
    def form_fields(self):
        if self.context.special:
            form_fields = grok.AutoFields(ICustomSpecialApplicant)
            form_fields['applicant_id'].for_display = True
            return form_fields
        target = getattr(self.context.__parent__, 'prefix', None)
        form_fields = grok.AutoFields(ICustomUGApplicant)
        for field in UG_OMIT_MANAGE_FIELDS:
            form_fields = form_fields.omit(field)
        form_fields['student_id'].for_display = True
        form_fields['applicant_id'].for_display = True
        return form_fields

class CustomApplicantEditFormPage(NigeriaApplicantEditFormPage):
    """An applicant-centered edit view for applicant data.
    """

    @property
    def form_fields(self):
        if self.context.special:
            form_fields = grok.AutoFields(ICustomSpecialApplicant).omit(
                'locked', 'suspended')
            form_fields['applicant_id'].for_display = True
            return form_fields
        target = getattr(self.context.__parent__, 'prefix', None)
        form_fields = grok.AutoFields(ICustomUGApplicantEdit)
        for field in UG_OMIT_EDIT_FIELDS:
            form_fields = form_fields.omit(field)
        form_fields['applicant_id'].for_display = True
        form_fields['reg_number'].for_display = True
        return form_fields

class CustomExportJobContainerOverview(ExportJobContainerOverview):

    grok.require('waeup.viewApplication')

class CustomExportJobContainerJobStart(ExportJobContainerJobStart):

    grok.require('waeup.viewApplication')

class CustomExportJobContainerDownload(ExportJobContainerDownload):

    grok.require('waeup.viewApplication')
