## $Id: browser.py 16407 2021-03-05 16:03:42Z 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
import os
from zope.i18n import translate
from zope.component import getUtility
from zope.security import checkPermission
from hurry.workflow.interfaces import IWorkflowInfo
from waeup.kofa.interfaces import ADMITTED, VALIDATED, IKofaUtils
from waeup.kofa.interfaces import MessageFactory as _
from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
from waeup.kofa.students.interfaces import IStudentsUtils
from waeup.kofa.students.browser import (
    StartClearancePage, 
    ExportPDFAdmissionSlip, StudyLevelDisplayFormPage,
    PaymentsManageFormPage,
    OnlinePaymentApproveView,
    StudentBasePDFFormPage)
from kofacustom.nigeria.students.browser import (
    NigeriaOnlinePaymentDisplayFormPage,
    NigeriaOnlinePaymentAddFormPage,
    NigeriaExportPDFPaymentSlip,
    NigeriaStudentClearanceEditFormPage,
    NigeriaExportPDFClearanceSlip,
    NigeriaExportPDFCourseRegistrationSlip,
    NigeriaBedTicketAddPage,
    NigeriaAccommodationManageFormPage,
    NigeriaAccommodationDisplayFormPage,
    )

from waeup.fceokene.students.interfaces import (
    ICustomStudentOnlinePayment, ICustomUGStudentClearance,
    ICustomStudentStudyLevel)

class CustomExportPDFAdmissionSlip(ExportPDFAdmissionSlip):
    """Deliver a PDF Admission slip.
    """

    @property
    def label(self):
        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
        line0 = ''
        if self.context.student.current_mode.startswith('ug'):
            line0 = 'IN AFFILIATION WITH UNIVERSITY OF IBADAN\n'
        line1 = translate(_('Admission Letter of'),
            'waeup.kofa', target_language=portal_language) \
            + ' %s' % self.context.display_fullname
        return '%s%s' % (line0, line1)

    @property
    def _post_text(self):
        return """You should note the following as conditions for admission:

1. At the point of registration, you will be required to present the originals of your certificate(s), 
   Jamb Original Result, a Birth Certificate or a Declaration of Age Certificate and Evidence of
   Citizenship Certificate.

2. Please note that the name by which you are hereby admitted and by which you will be registered 
   is the one which will appear on any certificate that the Federal College of Education, Okene may
   issue to you on successful completion of your programme except there was a change of name by 
   sworn affidavit or marriage certificate in addition to newspaper publication.

3. You are hereby informed that all fees must be paid at the beginning of the academic session. 
   The current school fees can be obtained from the College website.

4. You will present at the time of registration the Medical Certificate of Fitness from the Federal
   College of Education, Okene Medical Centre.

5. Please, note that due to shortage of accommodations, students shall be given accommodations
   on first come, first serve basis.

6. The offer is not transferable to another session.

7. You will sign a declaration of good conduct except by deferment on your arrival at the College.

Accept my congratulations.

Yours faithfully

Sheidu Usman, Hauwa
Deputy Registrar (Admissions)
For: Registrar
"""

    def render(self):
        students_utils = getUtility(IStudentsUtils)
        letterhead_path = os.path.join(
            os.path.dirname(__file__), 'static', 'letterhead_admission.jpg')
        topMargin=1.6
        if self.context.student.current_mode.startswith('ug'):
            letterhead_path = None
            topMargin=1.5
        return students_utils.renderPDFAdmissionLetter(self,
            self.context.student, omit_fields=self.omit_fields,
            letterhead_path=letterhead_path,
            topMargin=topMargin,
            post_text=self._post_text)

class CustomOnlinePaymentDisplayFormPage(NigeriaOnlinePaymentDisplayFormPage):
    """ Page to view an online payment ticket
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item', 'p_combi')
    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_combi')

class OnlinePaymentApproveView(OnlinePaymentApproveView):
    grok.require('waeup.manageStudent')

class CustomExportPDFPaymentSlip(NigeriaExportPDFPaymentSlip):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item', 'p_combi')
    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomStartClearancePage(StartClearancePage):

    @property
    def with_ac(self):
        mode = getattr(self.context, 'current_mode', None)
        if mode and mode.startswith('ug'):
            return True
        return False

class CustomExportPDFClearanceSlip(NigeriaExportPDFClearanceSlip):
    """Deliver a PDF slip of the context.
    """

    @property
    def form_fields(self):
        if self.context.is_postgrad:
            form_fields = grok.AutoFields(
                ICustomPGStudentClearance).omit('clearance_locked')
        else:
            form_fields = grok.AutoFields(
                ICustomUGStudentClearance).omit('clearance_locked')
        if not getattr(self.context, 'officer_comment'):
            form_fields = form_fields.omit('officer_comment')
        return form_fields

    @property
    def label(self):
        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE

        line0 = ''
        if self.context.student.current_mode.startswith('ug'):
            line0 = 'Directorate of Undergraduate Programme\n'
        line1 = translate(_('Clearance Slip of'),
            'waeup.kofa', target_language=portal_language) \
            + ' %s' % self.context.display_fullname
        return '%s%s' % (line0, line1)


class CustomStudentClearanceEditFormPage(NigeriaStudentClearanceEditFormPage):
    """ View to edit student clearance data by student
    """

    def dataNotComplete(self):
        return False

class CustomBedTicketAddPage(NigeriaBedTicketAddPage):
    """ Page to add an online payment ticket
    """
    buttonname = _('Create bed ticket')
    notice = ''
    with_ac = False
    with_bedselection = True

class CustomStudyLevelDisplayFormPage(StudyLevelDisplayFormPage):
    """ Page to display student study levels
    """
    grok.context(ICustomStudentStudyLevel)
    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit('level')
    form_fields[
        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomExportPDFCourseRegistrationSlip(
    NigeriaExportPDFCourseRegistrationSlip):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudentStudyLevel)
    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit('level')

class ExportPDFExaminationClearanceSlip1(CustomExportPDFCourseRegistrationSlip):
    """Deliver a PDF slip of the context.
    """
    grok.name('examination_clearance_slip_1.pdf')
    form_fields = None
    omit_fields = (
        'password', 'suspended', 'phone', 'date_of_birth',
        'parents_email', 'current_mode', 'entry_session',
        'adm_code', 'sex', 'suspended_comment', 
        'flash_notice')
    semester = 1
    tabletitle =  ['', '', '']

    @property
    def label(self):
        return '%s First Semester Examination Clearance' % self.context.level_session

    @property
    def title(self):
        return ''

    def update(self):
        if self.context.student.state != VALIDATED \
            or self.context.student.current_level != self.context.level:
            self.flash(_('Forbidden'), type="warning")
            self.redirect(self.url(self.context))

    def render(self):
        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
        Code = translate('Code', 'waeup.kofa', target_language=portal_language)
        studentview = StudentBasePDFFormPage(self.context.student,
            self.request, self.omit_fields)
        students_utils = getUtility(IStudentsUtils)

        tabledata = []
        tableheader = []
        for i in range(1,7):
            tabledata.append(sorted(
                [value for value in self.context.values() if i == self.semester == value.semester],
                key=lambda value: value.code))
            tableheader.append([(Code,'code', 2.5),
                             ('Invigilator\'s Name','inv', 8),
                             ('Signature and Date','sig', 7),
                             ])
        return students_utils.renderPDF(
            self, 'examination_clearance_slip_%s.pdf' % self.semester,
            self.context.student, studentview,
            tableheader=tableheader,
            tabledata=tabledata,
            omit_fields=self.omit_fields,
            topMargin=1.3
            )

class ExportPDFExaminationClearanceSlip2(ExportPDFExaminationClearanceSlip1):
    """Deliver a PDF slip of the context.
    """
    grok.name('examination_clearance_slip_2.pdf')
    semester = 2

    @property
    def label(self):
        return '%s Second Semester Examination Clearance' % self.context.level_session

class CustomPaymentsManageFormPage(PaymentsManageFormPage):
    """ Page to manage the student payments. This manage form page is for
    both students and students officers. FCEOkene does not allow students
    to remove any payment ticket.
    """
    @property
    def manage_payments_allowed(self):
        return checkPermission('waeup.manageStudent', self.context)

class CustomAccommodationDisplayFormPage(NigeriaAccommodationDisplayFormPage):
    """ Page to view bed tickets.
    """
    with_hostel_selection = True

class CustomAccommodationManageFormPage(NigeriaAccommodationManageFormPage):
    """ Page to manage bed tickets.
    This manage form page is for both students and students officers.
    """
    with_hostel_selection = True
