## $Id: browser.py 11786 2014-08-30 05:42:26Z 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.component import getUtility, createObject
from zope.security import checkPermission
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.browser.layout import action, UtilityView
from waeup.kofa.interfaces import IExtFileStore
from waeup.kofa.applicants.browser import (
    ApplicantRegistrationPage, ApplicantsContainerPage,
    ApplicationFeePaymentAddPage,
    OnlinePaymentApprovePage,
    ExportPDFPageApplicationSlip)
from waeup.kofa.applicants.interfaces import (
    ISpecialApplicant, IApplicantsUtils)
from kofacustom.nigeria.applicants.browser import (
    NigeriaApplicantDisplayFormPage,
    NigeriaApplicantManageFormPage,
    NigeriaPDFApplicationSlip)
from waeup.uniben.applicants.interfaces import (
    ICustomApplicant)
from waeup.kofa.applicants.workflow import ADMITTED, PAID

from waeup.uniben.interfaces import MessageFactory as _

PASTQ_ALL = ['ADT','EPCS','ESM','HEK','VTE']

PASTQ_AL = ['ENL','FAA','FOL','HIS','LAL',
            'PHL','THR','BUL','JIL','LAW','PPL','PUL'] + PASTQ_ALL

PASTQ_BS = ['ANT','ANY','CHH','COH','HAE','MED','MEH','PHS','SUR',
            'PCG','PCH','PCO', 'PCT','PHA','PHM','PMB','ANA','MBC',
            'MLS','NSC','PSY','DPV','ODR','OSP','PER', 'RES','AEB',
            'BCH','BOT','CED','EVL','MCB','OPT','PBB','SLT','ZOO',
            'AEE','ANS', 'CRS','FIS','FOW','SOS'] + PASTQ_ALL

PASTQ_EPS = ['CHE','CVE','DMIC','EEE','MCH','PEE','PRE','CHM',
             'CSC','GLY','MTH','PHY'] + PASTQ_ALL

PASTQ_MSS = ['ACC','BNK','BUS','ECO','GEO','POL','SAA','SWK'] + PASTQ_ALL

class CustomApplicantsContainerPage(ApplicantsContainerPage):
    """The standard view for regular applicant containers.
    """

    @property
    def form_fields(self):
        form_fields = super(CustomApplicantsContainerPage, self).form_fields
        usertype = getattr(self.request.principal, 'user_type', None)
        if self.request.principal.id == 'zope.anybody' or  \
            usertype in ('applicant', 'student'):
            return form_fields.omit('application_fee')
        return form_fields

class CustomApplicantRegistrationPage(ApplicantRegistrationPage):
    """Captcha'd registration page for applicants.
    """

    def _redirect(self, email, password, applicant_id):
        # Forward email and credentials to landing page.
        self.redirect(self.url(self.context, 'registration_complete',
            data = dict(email=email, password=password,
            applicant_id=applicant_id)))
        return

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

    def _show_pastq_putme(self):
        return self.target.startswith('putme') \
               and self.context.state in ('paid', 'submitted') \
               and getattr(self.context, 'course1') is not None

    @property
    def show_pastq_al(self):
        return self._show_pastq_putme() \
               and self.context.course1.__parent__.__parent__.code in PASTQ_AL

    @property
    def show_pastq_bs(self):
        return self._show_pastq_putme() \
               and self.context.course1.__parent__.__parent__.code in PASTQ_BS

    @property
    def show_pastq_eps(self):
        return self._show_pastq_putme() \
               and self.context.course1.__parent__.__parent__.code in PASTQ_EPS

    @property
    def show_pastq_mss(self):
        return self._show_pastq_putme() \
               and self.context.course1.__parent__.__parent__.code in PASTQ_MSS

    @property
    def show_pastq_pude(self):
        return self.target.startswith('pude') \
               and self.context.state in ('paid', 'submitted') 

    # Customizations for admission checking payments

    @property
    def form_fields(self):
        form_fields = super(CustomApplicantDisplayFormPage, self).form_fields
        if not self.context.admchecking_fee_paid():
            form_fields = form_fields.omit(
                'screening_score', 'aggregate', 'student_id')
        return form_fields

    @property
    def display_actions(self):
        state = IWorkflowState(self.context).getState()
        actions = []
        if state == ADMITTED 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.
        """
        course_admitted = self.context.course_admitted
        if getattr(course_admitted, '__parent__',None) and \
            self.context.admchecking_fee_paid():
            url = self.url(course_admitted)
            title = course_admitted.title
            code = course_admitted.code
            return '<a href="%s">%s - %s</a>' %(url,code,title)
        return ''

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

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

class CustomNigeriaPDFApplicationSlip(NigeriaPDFApplicationSlip):

    @property
    def note(self):
        if self.target is not None and not self.target.startswith('pg') \
            and not self._reduced_slip():
            return _(u'<br /><br /><br />'
                      'Comfirm your screening venue 72 hours to the screening. '
                      '<br /><br />'
                      'No bags, phones and calculators are allowed in the '
                      'screening venues.')
        return

class CustomApplicationFeePaymentAddPage(ApplicationFeePaymentAddPage):
    """ Page to add an online payment ticket
    """

    @property
    def custom_requirements(self):
        store = getUtility(IExtFileStore)
        if not store.getFileByContext(self.context, attr=u'passport.jpg'):
            return _('Upload your 1"x1" Red background passport photo before making payment.')
        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 CustomApplicantManageFormPage(NigeriaApplicantManageFormPage):

    @property
    def custom_upload_requirements(self):
        if not checkPermission('waeup.uploadPassportPictures', self.context):
            return _('You are not entitled to upload passport pictures.')

class CustomOnlinePaymentApprovePage(OnlinePaymentApprovePage):
    """ Approval view
    """


    def update(self):
        if self.context.p_category == 'admission_checking':
            if self.context.p_state == 'paid':
                flashtype = 'warning'
                msg = _('This ticket has already been paid.')
                log = None
            else:
                self.context.approve()
                log = 'payment approved: %s' % self.context.p_id
                msg = _('Payment approved')
                flashtype = 'success'
        else:
            flashtype, msg, log = self.context.approveApplicantPayment()
        if log is not None:
            applicant = self.context.__parent__
            # Add log message to applicants.log
            applicant.writeLogMessage(self, log)
            # Add log message to payments.log
            self.context.logger.info(
                '%s,%s,%s,%s,%s,,,,,,' % (
                applicant.applicant_id,
                self.context.p_id, self.context.p_category,
                self.context.amount_auth, self.context.r_code))
        self.flash(msg, type=flashtype)
        return

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


    def update(self):
        super(CustomExportPDFPageApplicationSlip, self).update()
        if self.context.state == ADMITTED 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
