## $Id: browser.py 15346 2019-03-06 22:19:56Z 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.component import getUtility
from zope.catalog.interfaces import ICatalog
from waeup.kofa.interfaces import academic_sessions_vocab, IKofaUtils
from waeup.kofa.payments.interfaces import IPayer
from waeup.kofa.webservices import PaymentDataWebservice
from kofacustom.nigeria.etranzact.helpers import ERROR_PART1, ERROR_PART2

class NigeriaPaymentDataWebservice(PaymentDataWebservice):
    """A simple webservice to publish payment and payer details on request from
    accepted IP addresses without authentication.

    Etranzact is asking for the PAYEE_ID which is indeed misleading.
    These are not the data of the payee but of the payer. And it's
    not the id of the payer but of the payment.
    """
    grok.name('feerequest')

    #ACCEPTED_IP = ('195.219.3.181', '195.219.3.184')
    ACCEPTED_IP = None

    CATEGORY_MAPPING = {
        'SCHOOLFEE': ('schoolfee',),
         }

    def update(self, PAYEE_ID=None, PAYMENT_TYPE=None):

        if PAYEE_ID == None:
            self.output = ERROR_PART1 + 'Missing PAYEE_ID' + ERROR_PART2
            return
        real_ip = self.request.get('HTTP_X_FORWARDED_FOR', None)
        # We can forego the logging once eTranzact payments run smoothly
        # and the accepted IP addresses are used.
        if real_ip:
            self.context.logger.info('PaymentDataWebservice called: %s' % real_ip)
        if real_ip  and self.ACCEPTED_IP:
            if real_ip not in  self.ACCEPTED_IP:
                self.output = ERROR_PART1 + 'Wrong IP address' + ERROR_PART2
                return
        payment_cats_dict = getUtility(IKofaUtils).PAYMENT_CATEGORIES
        if not PAYMENT_TYPE or (PAYMENT_TYPE not in self.CATEGORY_MAPPING.keys() \
            and PAYMENT_TYPE.lower() not in payment_cats_dict.keys()):
            self.output = ERROR_PART1 + 'Invalid PAYMENT_TYPE' + ERROR_PART2
            return
        cat = getUtility(ICatalog, name='payments_catalog')
        results = list(cat.searchResults(p_id=(PAYEE_ID, PAYEE_ID)))
        if len(results) != 1:
            self.output = ERROR_PART1 + 'Invalid PAYEE_ID' + ERROR_PART2
            return
        amount = results[0].amount_auth
        payment_type = results[0].category
        p_category = results[0].p_category
        programme_type = results[0].p_item
        if not programme_type:
            programme_type = 'N/A'
        academic_session = academic_sessions_vocab.getTerm(
            results[0].p_session).title
        status = results[0].p_state
        if status == 'paid':
            self.output = ERROR_PART1 + 'PAYEE_ID already used' + ERROR_PART2
            return
        if p_category not in self.CATEGORY_MAPPING.get(PAYMENT_TYPE, []) \
            and p_category != PAYMENT_TYPE.lower():
            self.output = ERROR_PART1 + 'Wrong PAYMENT_TYPE' + ERROR_PART2
            return
        try:
            owner = IPayer(results[0])
            full_name = owner.display_fullname
            matric_no = owner.matric_number
            faculty = owner.faculty
            department = owner.department
            study_type = owner.current_mode
            email = owner.email
            phone = owner.phone
            level = owner.current_level
        except (TypeError, AttributeError):
            self.output = ERROR_PART1 +  'Unknown error' + ERROR_PART2
            return
        self.output = (
            'PayeeName=%s~' +
            'Faculty=%s~' +
            'Department=%s~' +
            'Level=%s~' +
            'ProgrammeType=%s~' +
            'StudyType=%s~' +
            'Session=%s~' +
            'PayeeID=%s~' +
            'Amount=%s~' +
            'FeeStatus=%s~' +
            'Semester=N/A~' +
            'PaymentType=%s~' +
            'MatricNumber=%s~' +
            'Email=%s~' +
            'PhoneNumber=%s'

            ) % (full_name, faculty,
            department, level, programme_type, study_type,
            academic_session, PAYEE_ID, amount, status, payment_type,
            matric_no, email, phone)
        return