## $Id: utils.py 14229 2016-10-27 07:13:07Z 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
##
import grok
from time import time
from zope.component import createObject
from waeup.kofa.interfaces import (
    ADMITTED, CLEARANCE, REQUESTED, CLEARED, RETURNING, PAID,
    academic_sessions_vocab)
from kofacustom.nigeria.students.utils import NigeriaStudentsUtils
from waeup.kofa.accesscodes import create_accesscode
from waeup.kofa.students.utils import trans
from waeup.aaue.interswitch.browser import gateway_net_amt, GATEWAY_AMT
from waeup.aaue.interfaces import MessageFactory as _

class CustomStudentsUtils(NigeriaStudentsUtils):
    """A collection of customized methods.

    """

    PORTRAIT_CHANGE_STATES = (ADMITTED, RETURNING)

    gpa_boundaries = ((1, 'FRNS'),
                      (1.5, 'Pass'),
                      (2.4, '3rd Class Honours'),
                      (3.5, '2nd Class Honours Lower Division'),
                      (4.5, '2nd Class Honours Upper Division'),
                      (5, '1st Class Honours'))

    def getDegreeClassNumber(self, level_obj):
        certificate = getattr(level_obj.__parent__,'certificate',None)
        end_level = getattr(certificate, 'end_level', None)
        if end_level and level_obj.student.current_level >= end_level:
            failed_courses = level_obj.passed_params[4]
            if '_m' in failed_courses:
                return 0
        # use gpa_boundaries above
        return self.getClassFromCGPA(level_obj.cumulative_params[0])[0]

    def increaseMatricInteger(self, student):
        """Increase counter for matric numbers.
        This counter can be a centrally stored attribute or an attribute of
        faculties, departments or certificates. In the base package the counter
        is as an attribute of the site configuration container.
        """
        if student.current_mode in ('ug_pt', 'de_pt'):
            grok.getSite()['configuration'].next_matric_integer += 1
            return
        elif student.is_postgrad:
            grok.getSite()['configuration'].next_matric_integer_3 += 1
            return
        elif student.current_mode in ('dp_ft',):
            grok.getSite()['configuration'].next_matric_integer_4 += 1
            return
        grok.getSite()['configuration'].next_matric_integer_2 += 1
        return

    def _concessionalPaymentMade(self, student):
        if len(student['payments']):
            for ticket in student['payments'].values():
                if ticket.p_state == 'paid' and \
                    ticket.p_category == 'concessional':
                    return True
        return False

    def constructMatricNumber(self, student):
        faccode = student.faccode
        depcode = student.depcode
        certcode = student.certcode
        degree = getattr(
            getattr(student.get('studycourse', None), 'certificate', None),
                'degree', None)
        year = unicode(student.entry_session)[2:]
        if not student.state in (PAID, ) or not student.is_fresh or \
            student.current_mode == 'found':
            return _('Matriculation number cannot be set.'), None
        #if student.current_mode not in ('mug_ft', 'mde_ft') and \
        #    not self._concessionalPaymentMade(student):
        #    return _('Matriculation number cannot be set.'), None
        if student.is_postgrad:
            next_integer = grok.getSite()['configuration'].next_matric_integer_3
            if not degree or next_integer == 0:
                return _('Matriculation number cannot be set.'), None
            if student.faccode in ('IOE'):
                return None, "AAU/SPS/%s/%s/%s/%05d" % (
                    faccode, year, degree, next_integer)
            return None, "AAU/SPS/%s/%s/%s/%s/%05d" % (
                faccode, depcode, year, degree, next_integer)
        if student.current_mode in ('ug_pt', 'de_pt'):
            next_integer = grok.getSite()['configuration'].next_matric_integer
            if next_integer == 0:
                return _('Matriculation number cannot be set.'), None
            return None, "PTP/%s/%s/%s/%05d" % (
                faccode, depcode, year, next_integer)
        if student.current_mode in ('dp_ft',):
            next_integer = grok.getSite()['configuration'].next_matric_integer_4
            if next_integer == 0:
                return _('Matriculation number cannot be set.'), None
            return None, "IOE/DIP/%s/%05d" % (year, next_integer)
        next_integer = grok.getSite()['configuration'].next_matric_integer_2
        if next_integer == 0:
            return _('Matriculation number cannot be set.'), None
        if student.faccode in ('FBM', 'FCS'):
            return None, "CMS/%s/%s/%s/%05d" % (
                faccode, depcode, year, next_integer)
        return None, "%s/%s/%s/%05d" % (faccode, depcode, year, next_integer)

    def getReturningData(self, student):
        """ This method defines what happens after school fee payment
        of returning students depending on the student's senate verdict.
        """
        prev_level = student['studycourse'].current_level
        cur_verdict = student['studycourse'].current_verdict
        if cur_verdict in ('A','B','C', 'L','M','N','Z',):
            # Successful student
            new_level = divmod(int(prev_level),100)[0]*100 + 100
        #elif cur_verdict == 'C':
        #    # Student on probation
        #    new_level = int(prev_level) + 10
        else:
            # Student is somehow in an undefined state.
            # Level has to be set manually.
            new_level = prev_level
        new_session = student['studycourse'].current_session + 1
        return new_session, new_level

    def _isPaymentDisabled(self, p_session, category, student):
        academic_session = self._getSessionConfiguration(p_session)
        if category.startswith('schoolfee') and \
            'sf_all' in academic_session.payment_disabled:
            return True
        if category.startswith('clearance') and \
            'cl_regular' in academic_session.payment_disabled and \
            student.current_mode in ('ug_ft', 'de_ft', 'mug_ft', 'mde_ft'):
            return True
        if category == 'hostel_maintenance' and \
            'maint_all' in academic_session.payment_disabled:
            return True
        return False

    def setPaymentDetails(self, category, student,
            previous_session=None, previous_level=None):
        """Create Payment object and set the payment data of a student for
        the payment category specified.

        """
        details = {}
        p_item = u''
        amount = 0.0
        error = u''
        if previous_session:
            return _('Previous session payment not yet implemented.'), None
        p_session = student['studycourse'].current_session
        p_level = student['studycourse'].current_level
        p_current = True
        academic_session = self._getSessionConfiguration(p_session)
        if academic_session == None:
            return _(u'Session configuration object is not available.'), None
        # Determine fee.
        if category == 'transfer':
            amount = academic_session.transfer_fee
        elif category == 'transcript':
            amount = academic_session.transcript_fee
        elif category == 'bed_allocation':
            amount = academic_session.booking_fee
        elif category == 'hostel_maintenance':
            amount = 0.0
            bedticket = student['accommodation'].get(
                str(student.current_session), None)
            if bedticket is not None and bedticket.bed is not None:
                p_item = bedticket.display_coordinates
                if bedticket.bed.__parent__.maint_fee > 0:
                    amount = bedticket.bed.__parent__.maint_fee
                else:
                    # fallback
                    amount = academic_session.maint_fee
            else:
                return _(u'No bed allocated.'), None
        elif category == 'welfare' and not student.is_postgrad:
            amount = academic_session.welfare_fee
        elif category == 'union' and not student.is_postgrad:
            amount = academic_session.union_fee
        elif category == 'lapel' and not student.is_postgrad:
            amount = academic_session.lapel_fee
        elif category == 'matric_gown' and not student.is_postgrad:
            amount = academic_session.matric_gown_fee
        elif category == 'concessional' and not student.is_postgrad:
            amount = academic_session.concessional_fee
        elif student.current_mode == 'found' and category not in (
            'schoolfee', 'clearance', 'late_registration'):
            return _('Not allowed.'), None
        elif category.startswith('clearance'):
            if student.state not in (ADMITTED, CLEARANCE, REQUESTED, CLEARED):
                return _(u'Acceptance Fee payments not allowed.'), None
            if student.current_mode in (
                'ug_ft', 'ug_pt', 'de_ft', 'de_pt',
                'transfer', 'mug_ft', 'mde_ft') \
                and category != 'clearance_incl':
                    return _("Additional fees must be included."), None
            if student.faccode == 'FP':
                amount = academic_session.clearance_fee_fp
            elif student.current_mode.endswith('_pt'):
                if student.is_postgrad:
                    amount = academic_session.clearance_fee_pg_pt
                else:
                    amount = academic_session.clearance_fee_ug_pt
            elif student.faccode == 'FCS':
                # Students in clinical medical sciences pay the medical
                # acceptance fee
                amount = academic_session.clearance_fee_med
            elif student.is_postgrad:  # and not part-time
                if category != 'clearance':
                    return _("No additional fees required."), None
                amount = academic_session.clearance_fee_pg
            else:
                amount = academic_session.clearance_fee
            p_item = student['studycourse'].certificate.code
            if amount in (0.0, None):
                return _(u'Amount could not be determined.'), None
            # Add Matric Gown Fee and Lapel Fee
            if category == 'clearance_incl':
                amount += gateway_net_amt(academic_session.matric_gown_fee) + \
                    gateway_net_amt(academic_session.lapel_fee)
        elif category == 'late_registration':
            if student.is_postgrad:
                amount = academic_session.late_pg_registration_fee
            else:
                amount = academic_session.late_registration_fee
        elif category.startswith('schoolfee'):
            try:
                certificate = student['studycourse'].certificate
                p_item = certificate.code
            except (AttributeError, TypeError):
                return _('Study course data are incomplete.'), None
            if student.is_postgrad and category != 'schoolfee':
                return _("No additional fees required."), None
            if student.current_mode in (
                'ug_ft', 'ug_pt', 'de_ft', 'de_pt',
                'transfer', 'mug_ft', 'mde_ft') \
                and not category in (
                'schoolfee_incl', 'schoolfee_1', 'schoolfee_2'):
                    return _("You must chose a payment which includes "
                             "additional fees."), None
            if category in ('schoolfee_1', 'schoolfee_2'):
                if student.current_mode == 'ug_pt':
                    return _("Part-time students are not allowed "
                             "to pay by instalments."), None
                if category == 'schoolfee_1' and student.state != CLEARED:
                    return _("Wrong state. Only students in state 'cleared' "
                             "are allowed to pay by instalments."), None
                if category == 'schoolfee_2' and not student.is_fresh:
                    return _("Only new students "
                             "are allowed to pay by instalments."), None
            if student.state == CLEARED or category == 'schoolfee_2':
                amount = getattr(certificate, 'school_fee_1', 0.0)
                # Cut school fee by 50%
                if category in ('schoolfee_1', 'schoolfee_2'):
                    if amount:
                        amount = gateway_net_amt(amount) / 2 + GATEWAY_AMT
            elif student.state == RETURNING:
                if not student.father_name:
                    return _("Personal data form is not properly filled."), None
                # In case of returning school fee payment the payment session
                # and level contain the values of the session the student
                # has paid for.
                p_session, p_level = self.getReturningData(student)
                try:
                    academic_session = grok.getSite()[
                        'configuration'][str(p_session)]
                except KeyError:
                    return _(u'Session configuration object is not available.'), None
                if student.entry_session == 2015:
                    amount = getattr(certificate, 'school_fee_2', 0.0)
                else:
                    amount = getattr(certificate, 'school_fee_3', 0.0)
            else:
                return _('Wrong state.'), None
            if amount in (0.0, None):
                return _(u'Amount could not be determined.'), None
            # Add Student Union Fee and Welfare Assurance
            if category in ('schoolfee_incl', 'schoolfee_1'):
                amount += gateway_net_amt(academic_session.welfare_fee) + \
                    gateway_net_amt(academic_session.union_fee)
            # Add non-indigenous fee and session specific penalty fees
            if student.is_postgrad:
                amount += academic_session.penalty_pg
                if not student.lga.startswith('edo'):
                    amount += 20000.0
            else:
                amount += academic_session.penalty_ug
        if amount in (0.0, None):
            return _(u'Amount could not be determined.'), None
        # Create ticket.
        for key in student['payments'].keys():
            ticket = student['payments'][key]
            if ticket.p_state == 'paid' and\
               ticket.p_category == category and \
               ticket.p_item == p_item and \
               ticket.p_session == p_session:
                  return _('This type of payment has already been made.'), None
            # Additional condition in AAUE
            if category in ('schoolfee', 'schoolfee_incl', 'schoolfee_1'):
                if ticket.p_state == 'paid' and \
                   ticket.p_category in ('schoolfee',
                                         'schoolfee_incl',
                                         'schoolfee_1') and \
                   ticket.p_item == p_item and \
                   ticket.p_session == p_session:
                      return _(
                          'Another school fee payment for this '
                          'session has already been made.'), None

        if self._isPaymentDisabled(p_session, category, student):
            return _('This category of payments has been disabled.'), None
        payment = createObject(u'waeup.StudentOnlinePayment')
        timestamp = ("%d" % int(time()*10000))[1:]
        payment.p_id = "p%s" % timestamp
        payment.p_category = category
        payment.p_item = p_item
        payment.p_session = p_session
        payment.p_level = p_level
        payment.p_current = p_current
        payment.amount_auth = amount
        return None, payment

    def _admissionText(self, student, portal_language):
        inst_name = grok.getSite()['configuration'].name
        entry_session = student['studycourse'].entry_session
        entry_session = academic_sessions_vocab.getTerm(entry_session).title
        text = trans(_(
            'This is to inform you that you have been offered provisional'
            ' admission into ${a} for the ${b} academic session as follows:',
            mapping = {'a': inst_name, 'b': entry_session}),
            portal_language)
        return text

    def maxCredits(self, studylevel):
        """Return maximum credits.

        """
        return 48

    def getBedCoordinates(self, bedticket):
        """Return descriptive bed coordinates.
        This method can be used to customize the `display_coordinates`
        property method in order to  display a
        customary description of the bed space.
        """
        bc = bedticket.bed_coordinates.split(',')
        if len(bc) == 4:
            return bc[0]
        return bedticket.bed_coordinates

    def getAccommodationDetails(self, student):
        """Determine the accommodation data of a student.
        """
        d = {}
        d['error'] = u''
        hostels = grok.getSite()['hostels']
        d['booking_session'] = hostels.accommodation_session
        d['allowed_states'] = hostels.accommodation_states
        d['startdate'] = hostels.startdate
        d['enddate'] = hostels.enddate
        d['expired'] = hostels.expired
        # Determine bed type
        bt = 'all'
        if student.sex == 'f':
            sex = 'female'
        else:
            sex = 'male'
        special_handling = 'regular'
        d['bt'] = u'%s_%s_%s' % (special_handling,sex,bt)
        return d

    def checkAccommodationRequirements(self, student, acc_details):
        super(CustomStudentsUtils, self).checkAccommodationRequirements(
            student, acc_details)
        if student.current_mode not in ('ug_ft', 'de_ft', 'mug_ft', 'mde_ft'):
            return _('You are not eligible to book accommodation.')
        return

    # AAUE prefix
    STUDENT_ID_PREFIX = u'E'