## $Id: browser.py 8722 2012-06-14 08:07:41Z 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
from zope.formlib.textwidgets import BytesDisplayWidget
from zope.component import getUtility
from zope.i18n import translate
from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
from waeup.kofa.interfaces import IExtFileStore
from waeup.kofa.browser.layout import action
from waeup.kofa.students.browser import (
    StudentPersonalDisplayFormPage,
    StudentClearanceManageFormPage, StudentClearanceEditFormPage,
    StudentClearanceDisplayFormPage, OnlinePaymentFakeApprovePage,
    ExportPDFClearanceSlipPage, StudentBaseManageFormPage,
    StudentBaseEditFormPage, StudentPersonalEditFormPage,
    OnlinePaymentDisplayFormPage, OnlinePaymentAddFormPage,
    OnlinePaymentBreadcrumb, ExportPDFPaymentSlipPage,
    StudentFilesUploadPage, emit_lock_message)
from waeup.kofa.students.viewlets import (
    PaymentReceiptActionButton, StudentPassportActionButton)
from waeup.fceokene.students.interfaces import (
    ICustomStudentBase, ICustomStudent, ICustomStudentPersonal,
    ICustomUGStudentClearance,ICustomPGStudentClearance,
    ICustomStudentOnlinePayment,
    )
from waeup.fceokene.interfaces import MessageFactory as _
from waeup.kofa.students.workflow import ADMITTED

#class RequestCallbackActionButton(RequestCallbackActionButton):
#    """ Display the base package callback button in custom pages.
#    """
#    grok.context(ICustomStudentOnlinePayment)

#class CustomOnlinePaymentCallbackPage(OnlinePaymentCallbackPage):
#    """ Activate callback simulation view
#    """
#    grok.context(ICustomStudentOnlinePayment)

class CustomOnlinePaymentBreadcrumb(OnlinePaymentBreadcrumb):
    """A breadcrumb for payments.
    """
    grok.context(ICustomStudentOnlinePayment)

class PaymentReceiptActionButton(PaymentReceiptActionButton):
    grok.order(4)
    grok.context(ICustomStudentOnlinePayment)

class CustomStudentBaseManageFormPage(StudentBaseManageFormPage):
    """ View to manage student base data
    """
    form_fields = grok.AutoFields(ICustomStudentBase).omit('student_id')

class CustomStudentBaseEditFormPage(StudentBaseEditFormPage):
    """ View to edit student base data
    """
    form_fields = grok.AutoFields(ICustomStudentBase).select(
        'email', 'phone')


class CustomStudentPersonalDisplayFormPage(StudentPersonalDisplayFormPage):
    """ Page to display student personal data
    """
    grok.context(ICustomStudent)
    form_fields = grok.AutoFields(ICustomStudentPersonal)
    form_fields['perm_address'].custom_widget = BytesDisplayWidget


class CustomStudentPersonalEditFormPage(StudentPersonalEditFormPage):
    """ Page to edit personal data
    """
    form_fields = grok.AutoFields(ICustomStudentPersonal)


class CustomStudentClearanceDisplayFormPage(StudentClearanceDisplayFormPage):
    """ Page to display student clearance data
    """
    grok.context(ICustomStudent)

    @property
    def form_fields(self):
        cm = getattr(self.context,'current_mode', None)
        if cm is not None and cm.startswith('pg'):
            form_fields = grok.AutoFields(
                ICustomPGStudentClearance).omit('clearance_locked')
        else:
            form_fields = grok.AutoFields(
                ICustomUGStudentClearance).omit('clearance_locked')
        return form_fields

class CustomExportPDFClearanceSlipPage(ExportPDFClearanceSlipPage):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudent)

    @property
    def form_fields(self):
        cm = getattr(self.context,'current_mode', None)
        if cm is not None and cm.startswith('pg'):
            form_fields = grok.AutoFields(
                ICustomPGStudentClearance).omit('clearance_locked')
        else:
            form_fields = grok.AutoFields(
                ICustomUGStudentClearance).omit('clearance_locked')
        return form_fields

class CustomStudentClearanceManageFormPage(StudentClearanceManageFormPage):
    """ Page to edit student clearance data
    """
    grok.context(ICustomStudent)

    @property
    def form_fields(self):
        cm = getattr(self.context,'current_mode', None)
        if cm is not None and cm.startswith('pg'):
            form_fields = grok.AutoFields(ICustomPGStudentClearance)
        else:
            form_fields = grok.AutoFields(ICustomUGStudentClearance)
        return form_fields

class CustomStudentClearanceEditFormPage(StudentClearanceEditFormPage):
    """ View to edit student clearance data by student
    """
    grok.context(ICustomStudent)

    @property
    def form_fields(self):
        cm = getattr(self.context,'current_mode', None)
        if cm is not None and cm.startswith('pg'):
            form_fields = grok.AutoFields(ICustomPGStudentClearance).omit('clearance_locked')
        else:
            form_fields = grok.AutoFields(ICustomUGStudentClearance).omit('clearance_locked')
        return form_fields

    def dataNotComplete(self):
        store = getUtility(IExtFileStore)
        if not store.getFileByContext(self.context, attr=u'birth_certicicate.jpg'):
            return _('No birth certificate uploaded.')
        if not store.getFileByContext(self.context, attr=u'ref_let.jpg'):
            return _('No referee letter uploaded.')
        if not store.getFileByContext(self.context, attr=u'acc_let.jpg'):
            return _('No acceptance letter uploaded.')
        if not store.getFileByContext(self.context, attr=u'fst_sit_scan.jpg'):
            return _('No first sitting result uploaded.')
        return False

class CustomOnlinePaymentDisplayFormPage(OnlinePaymentDisplayFormPage):
    """ Page to view an online payment ticket
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment)
    form_fields[
        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields[
        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    #grok.template('payment_view')

    #@property
    #def transaction_code(self):
    #    tcode = self.context.p_id
    #    return tcode[len(tcode)-8:len(tcode)]

class CustomOnlinePaymentAddFormPage(OnlinePaymentAddFormPage):
    """ Page to add an online payment ticket
    """
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).select(
        'p_category')

class CustomOnlinePaymentFakeApprovePage(OnlinePaymentFakeApprovePage):
    """ Disable payment approval view for students.

    This view is used for browser tests only and
    has to be neutralized here!
    """

    grok.name('fake_approve')
    grok.require('waeup.managePortal')

    def update(self):
        return

class CustomExportPDFPaymentSlipPage(ExportPDFPaymentSlipPage):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudentOnlinePayment)
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment)
    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

#    @property
#    def note(self):
#        tcode = self.context.p_id
#        tcode = tcode[len(tcode)-8:len(tcode)]
#        amount = self.context.amount_auth
#        note = translate(_(
#            u"""<br /><br /><br />
#The tranzaction code is <strong>${a}</strong>.""",
#            mapping = {'a':tcode}))
#        return note

class StudentPassportActionButton(StudentPassportActionButton):

    @property
    def note(self):
        tcode = self.context.p_id
        tcode = tcode[len(tcode)-8:len(tcode)]
        amount = self.context.amount_auth
        note = translate(_(
            u"""<br /><br /><br />
The tranzaction code for eTranzact payments is <strong>${a}</strong>.""",
            mapping = {'a':tcode}))
        return note
    def target_url(self):
        slip = getUtility(IExtFileStore).getFileByContext(
            self.context, 'application_slip')
        if self.context.state != ADMITTED or slip is not None:
            return ''
        return self.view.url(self.view.context, self.target)

class CustomStudentFilesUploadPage(StudentFilesUploadPage):
    """ View to upload passport picture.

    Students are not allowed to change the picture if they
    passed the regular Kofa application.
    """

    def update(self):
        slip = getUtility(IExtFileStore).getFileByContext(
            self.context, 'application_slip')
        if self.context.state != ADMITTED or slip is not None:
            emit_lock_message(self)
            return
        super(StudentFilesUploadPage, self).update()
        return