## $Id: export.py 12084 2014-11-28 09:54:10Z henrik $
##
## Copyright (C) 2015 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
##
"""Exporters for student related stuff.
"""
import grok
import os
from datetime import datetime
from waeup.kofa.interfaces import (
    IExtFileStore, IFileStoreNameChooser, IKofaUtils)
from zope.component import getUtility
from waeup.uniben.students.interfaces import (
    ICustomStudent,
    ICustomStudentStudyCourse,
    ICustomStudentStudyLevel,
    ICustomCourseTicket,
    ICustomStudentOnlinePayment,
    IMedicalHistory)
from kofacustom.nigeria.students.export import (
    NigeriaStudentExporter,
    NigeriaStudentStudyCourseExporter,
    NigeriaStudentStudyLevelExporter,
    NigeriaCourseTicketExporter,
    NigeriaStudentPaymentExporter,
    NigeriaDataForBursaryExporter,
    NigeriaTrimmedDataExporter,
    )
from waeup.kofa.students.export import (
    SchoolFeePaymentsOverviewExporter, StudentExporterBase)
from waeup.kofa.utils.helpers import iface_names

class CustomStudentExporter(NigeriaStudentExporter):
    """Exporter for Students.
    """

    fields = tuple(sorted(iface_names(
        ICustomStudent, omit=['loggerInfo']))) + (
        'password', 'state', 'history', 'certcode', 'is_postgrad',
        'current_level', 'current_session')

class CustomTrimmedDataExporter(NigeriaTrimmedDataExporter):
    """The Student Trimmed Data Exporter first filters the set of students
    by searching the students catalog. Then it exports a trimmed data set
    of this set of students.
    """
    fields = (
        'student_id',
        'matric_number',
        'reg_number',
        'firstname',
        'middlename',
        'lastname',
        'sex',
        'email',
        'email2',
        'phone',
        'perm_address',
        'nationality',
        'date_of_birth',
        'state',
        'current_mode',
        'certcode',
        'faccode',
        'depcode',
        'current_level',
        'current_session',
        'current_verdict',
        'entry_session',
        'lg_state',
        'lg_area',
        'flash_notice',
        'physical_clearance_date',
        'former_matric',
        'hq_matric_no',
        'hq2_matric_no',
        )

    #def mangle_value(self, value, name, context=None):
    #    if name == 'routing_slip_path':
    #        file_id = IFileStoreNameChooser(context).chooseName(
    #            attr='routingslip.pdf')
    #        os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
    #        if not os.path.exists(os_path):
    #            value = None
    #        else:
    #            value = '/'.join(os_path.split('/')[-4:])
    #    return super(
    #        CustomTrimmedDataExporter, self).mangle_value(
    #        value, name, context=context)


class CustomStudentStudyCourseExporter(NigeriaStudentStudyCourseExporter):
    """Exporter for StudentStudyCourses.
    """

    fields = tuple(
        sorted(iface_names(ICustomStudentStudyCourse))) + (
            'student_id', 'previous')

class CustomStudentStudyLevelExporter(NigeriaStudentStudyLevelExporter):
    """Exporter for StudentStudyLevels.
    """
    #: Fieldnames considered by this exporter
    fields = tuple(sorted(iface_names(
        ICustomStudentStudyLevel))) + (
        'student_id', 'number_of_tickets','certcode', 'previous')

class CustomCourseTicketExporter(NigeriaCourseTicketExporter):
    """Exporter for CourseTickets.
    """

    fields = tuple(sorted(iface_names(ICustomCourseTicket) +
        ['level', 'code', 'level_session'])) + ('student_id',
        'certcode', 'display_fullname', 'previous', 'matric_number')

class CustomStudentPaymentExporter(NigeriaStudentPaymentExporter):
    """Exporter for OnlinePayment instances.
    """

    fields = tuple(
        sorted(iface_names(
            ICustomStudentOnlinePayment, exclude_attribs=False,
            omit=['display_item']))) + (
            'student_id','state','current_session')

class CustomDataForBursaryExporter(NigeriaDataForBursaryExporter):
    """
    """

    fields = tuple(
        sorted(iface_names(
            ICustomStudentOnlinePayment, exclude_attribs=False,
            omit=['display_item', 'certificate', 'student']))) + (
            'student_id','matric_number','reg_number',
            'firstname', 'middlename', 'lastname',
            'state','current_session',
            'entry_session', 'entry_mode',
            'faccode', 'depcode','certcode')

class CustomSchoolFeePaymentsOverviewExporter(SchoolFeePaymentsOverviewExporter):

    curr_year = datetime.now().year
    year_range = range(curr_year - 14, curr_year + 1) # 3 more years in Uniben
    year_range_tuple = tuple([str(year) for year in year_range])

    fields = ('student_id', 'matric_number', 'firstname', 'middlename',
        'lastname', 'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
        'current_level', 'current_session', 'current_mode',
        'entry_session', 'reg_number', 'email2', 'sex'
        ) + year_range_tuple

class MedicalHistoryExporter(grok.GlobalUtility, StudentExporterBase):
    """
    """
    grok.name('medicalhistory')

    fields = tuple(
        sorted(iface_names(
            IMedicalHistory, exclude_attribs=False,))) + (
            'student_id','display_fullname', 'matric_number', 'faccode',
            'depcode', 'state','current_session', 'current_level', 'genotype', 'bloodgroup')
    title = 'Medical Questionnaire Data'

    def mangle_value(self, value, name, context=None):
        """The mangler determines the titles of faculty, department
        and certificate. It also computes the path of passport image file
        stored in the filesystem.
        """
        if context is not None:
            student = context.student
            if name in ('student_id','display_fullname',
                'matric_number', 'faccode',
                'depcode', 'state','current_session',
                'current_level',
                'genotype', 'bloodgroup') and student is not None:
                value = getattr(student, name, None)
        return super(
            MedicalHistoryExporter, self).mangle_value(
            value, name, context=context)

def get_routingslip_exists(students, **kw):
    """Get students with outstanding certificate courses.
    """
    students_with_slip = []
    for student in students:
        file_id = IFileStoreNameChooser(student).chooseName(
            attr='routingslip.pdf')
        os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
        if os.path.exists(os_path):
            students_with_slip.append(student)
    return students_with_slip

class RoutingSlipExporter(grok.GlobalUtility, StudentExporterBase):
    """
    """
    grok.name('routingslip')

    fields = ('student_id', 'matric_number',)
    title = 'Routing Slip Exists'

    def filter_func(self, x, **kw):
        return get_routingslip_exists(x, **kw)

    #def mangle_value(self, value, name, context=None):
    #    if name == 'routing_slip':
    #        file_id = IFileStoreNameChooser(context).chooseName(
    #            attr='routingslip.pdf')
    #        os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
    #        if not os.path.exists(os_path):
    #            value = None
    #        else:
    #            value = '1'
    #    return super(
    #        RoutingSlipExporter, self).mangle_value(
    #        value, name, context=context)


class NYSCExporter(SchoolFeePaymentsOverviewExporter):
    """
    """
    grok.name('nysc')
    curr_year = datetime.now().year
    year_range = range(curr_year - 11, curr_year + 1)
    year_range_tuple = tuple([str(year) for year in year_range])
    fields = ('student_id',
        'matric_number',
        'reg_number',
        'firstname',
        'middlename',
        'lastname',
        'sex',
        'email',
        'email2',
        'phone',
        'nationality',
        'date_of_birth',
        'state',
        'lg_state',
        'lg_area',
        'current_mode',
        'certificate',
        'faccode',
        'depcode',
        'current_level',
        'current_session',
        'current_verdict',
        'entry_session',
        'nysc_verdict',
        'nysc_senate_info',
        'nysc_date_of_graduation',
        'nysc_updated',
        'nysc_processed',
        ) + year_range_tuple
    title = u'NYSC Indication'

    def filter_func(self, x, **kw):
        students = list()
        for student in x:
            if student.nysc == True and student.nysc_processed == False:
                students.append(student)
        return students

    def mangle_value(self, value, name, context=None):
        verdicts = getUtility(IKofaUtils).VERDICTS_DICT
        if name in ('lg_state', 'lg_area') and context.lga:
            value = context.lga
            if value.startswith('cross_river') or value.startswith('akwa_ibom'):
                value = context.lga.replace('_', '-', 1)
            if name == 'lg_state':
                value = value.split('_')[0]
            if name == 'lg_area':
                value = '-'.join(value.split('_')[1:])
        if name == 'certificate':
            cert = getattr(context.get('studycourse', None), 'certificate', None)
            if cert is not None:
                value = cert.title
        if name == 'nysc_verdict' and value:
            value = verdicts[value]
        return super(
            NYSCExporter, self).mangle_value(
            value, name, context=context)