## $Id: utils.py 8775 2012-06-22 16:40:39Z 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 CLEARED, RETURNING, PAID
from waeup.kofa.students.utils import StudentsUtils
from waeup.kofa.students.interfaces import IStudentsUtils
from waeup.kofa.accesscodes import create_accesscode
from waeup.aaue.interfaces import MessageFactory as _

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

    """
    grok.implements(IStudentsUtils)

    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','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 setPaymentDetails(self, category, student):
        """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''
        p_session = student['studycourse'].current_session
        p_level = student['studycourse'].current_level
        session = str(p_session)
        try:
            academic_session = grok.getSite()['configuration'][session]
        except KeyError:
            return _(u'Session configuration object is not available.'), None
        # Determine fee.
        if category == 'schoolfee':
            return _('School fee has to be paid by two instalments.'), None
        if category == 'transfer':
            amount = academic_session.transfer_fee
        elif category == 'gown':
            amount = academic_session.gown_fee
        elif category == 'bed_allocation':
            amount = academic_session.booking_fee
        elif category == 'hostel_maintenance':
            amount = academic_session.maint_fee
        elif category == 'clearance':
            amount = academic_session.clearance_fee
            p_item = student['studycourse'].certificate.code
        elif category == 'schoolfee_1':
            try:
                certificate = student['studycourse'].certificate
                p_item = certificate.code
            except (AttributeError, TypeError):
                return _('Study course data are incomplete.'), None
            payment_allowed = False
            if student.state == CLEARED:
                payment_allowed = True
                amount = academic_session.school_fee_base
            elif student.state == RETURNING:
                p_session, p_level = self.getReturningData(student)
                initial_instalment_made = False
                for key in student['payments'].keys():
                    ticket = student['payments'][key]
                    if ticket.p_category == 'schoolfee_1' and \
                        ticket.p_state == 'paid':
                        initial_instalment_made = True
                    if ticket.p_state == 'paid' and\
                        ticket.p_category == 'schoolfee_2' and \
                        ticket.p_item == p_item and \
                        ticket.p_session == p_session-1: #  = current session
                        payment_allowed = True
                if not initial_instalment_made:
                    payment_allowed = True
                amount = academic_session.school_fee_base
            else:
                return _('Wrong state.'), None
            if not payment_allowed:
                return _('The previous 2nd school fee instalment '
                         'has not yet been paid.'), None
        elif category == 'schoolfee_2':
            try:
                certificate = student['studycourse'].certificate
                p_item = certificate.code
            except (AttributeError, TypeError):
                return _('Study course data are incomplete.'), None
            payment_allowed = False
            for key in student['payments'].keys():
                ticket = student['payments'][key]
                if ticket.p_state == 'paid' and\
                   ticket.p_category == 'schoolfee_1' and \
                   ticket.p_item == p_item and \
                   ticket.p_session == p_session:
                   payment_allowed = True
            if not payment_allowed:
                return _('The 1st school fee instalment '
                         'has not yet been paid or session has '
                         'not yet been started.'), None
            amount = academic_session.school_fee_base
        if amount in (0.0, None):
            return _(u'Amount could not be determined.'), None
        # Add session specific penalty fee.
        if category == 'schoolfee_1' and student.is_postgrad:
            amount += academic_session.penalty_pg
        elif category == 'schoolfee_1':
            amount += academic_session.penalty_ug
        # 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
        payment = createObject(u'waeup.StudentOnlinePayment')
        timestamp = "%d" % int(time()*1000)
        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.amount_auth = amount
        return None, payment

    VERDICTS_DICT = {
        'NY': 'not yet',
        'A': 'Successful student',
        'B': 'Student with carryover courses',
        'C': 'Student on probation',
        'D': 'Withdrawn from the faculty',
        'E': 'Student who were previously on probation',
        'F': 'Medical case',
        'G': 'Absent from examination',
        'H': 'Withheld results',
        'I': 'Expelled/rusticated/suspended student',
        'J': 'Temporary withdrawn from the university',
        'K': 'Unregistered student',
        'L': 'Referred student',
        'M': 'Reinstatement',
        'N': 'Student on transfer',
        'O': 'NCE-III repeater',
        'Y': 'No previous verdict',
        'X': 'New 300 level student',
        'Z': 'Successful student (provisional)',
        'A1': 'First Class',
        'A2': 'Second Class Upper',
        'A3': 'Second Class Lower',
        'A4': 'Third Class',
        'A5': 'Pass',
        'A6': 'Distinction',
        'A7': 'Credit',
        'A8': 'Merit',
        }

    # AAUE separators
    SEPARATORS_DICT = {
        'form.fst_sit_fname': _(u'First Sitting Record'),
        'form.scd_sit_fname': _(u'Second Sitting Record'),
        'form.alr_fname': _(u'Advanced Level Record'),
        'form.hq_type': _(u'Higher Education Record'),
        'form.hq2_type': _(u'Second Higher Education Record'),
        'form.nysc_year': _(u'NYSC Information'),
        'form.employer': _(u'Employment History'),
        'form.former_matric': _(u'Former AAUE Student'),
        }

    # AAUE prefix
    STUDENT_ID_PREFIX = u'E'