## $Id: tests.py 15468 2019-06-20 16:17:46Z henrik $
##
## Copyright (C) 2017 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 os
import unittest
import random
import json
import hashlib
from datetime import datetime, timedelta, date
from zope.component import createObject, getUtility
from zope.catalog.interfaces import ICatalog
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.students.tests.test_browser import StudentsFullSetup
from waeup.kofa.applicants.tests.test_browser import ApplicantsFullSetup
from waeup.kofa.configuration import SessionConfiguration
from kofacustom.nigeria.students.payments import NigeriaStudentOnlinePayment
from kofacustom.nigeria.testing import FunctionalLayer
from kofacustom.nigeria.etranzact.helpers import (
    get_query_response, get_caller_response)

#from kofacustom.nigeria.etranzact.helpers import (query_etranzact)

# Also run tests that send requests to external servers?
#   If you enable this, please make sure the external services
#   do exist really and are not bothered by being spammed by a test programme.

EXTERNAL_TESTS = True

TERMINAL_ID = '0000000001'
HOST = 'demo.etranzact.com'
HTTPS = True
SECRET_KEY = 'DEMO_KEY'
LOGO_URL = 'https://iuokada.waeup.org/static_custom/iou_logo.png'

def external_test(func):
    if not EXTERNAL_TESTS:
        myself = __file__
        if myself.endswith('.pyc'):
            myself = myself[:-1]
        print "WARNING: external tests are skipped!"
        print "WARNING: edit %s to enable them." % myself
        return
    return func

class HelperTests(unittest.TestCase):

    terminal_id = TERMINAL_ID

    def _create_transaction(self, transaction_id):
        responseurl = 'http://xxxx'
        amount = '4444.0'
        email = 'aa@aa.ng'
        phone = '12324'
        display_fullname = 'Tester'
        logo_url = 'http://xxxx'
        hashargs = 	amount + self.terminal_id + transaction_id \
            + responseurl + 'DEMO_KEY'
        hashvalue = hashlib.md5(hashargs).hexdigest()
        response = get_caller_response(HOST, HTTPS, self.terminal_id,
                                       transaction_id, responseurl,
                                       amount, email, phone,
                                       display_fullname, hashvalue,
                                       logo_url)
        return response

    @external_test
    def test_query_etranzact(self):
        transaction_id = str(random.randint(100000000, 999999999))
        response = get_query_response(HOST, self.terminal_id,
                                transaction_id, HTTPS)
        self.assertEqual(
            response,
            'Transaction with the given transaction_id (%s) not found'
            % transaction_id)
        # Okay, let's create a transaction
        caller_response = self._create_transaction(transaction_id)
        self.assertEqual(caller_response, None)
        # It seems that the transaction has been created but we don't get a
        # useful response
        query_response = get_query_response(HOST, self.terminal_id,
                                transaction_id, HTTPS)
        self.assertEqual(query_response, '')
        # The same, an 'empty' response obviously means that the transaction
        # was found. The result was probably sent to the response_url.
        return

class EtranzactTestsApplicants(ApplicantsFullSetup):
    """Tests for the Etranzact payment gateway.
    """

    layer = FunctionalLayer

    def setUp(self):
        super(EtranzactTestsApplicants, self).setUp()
        configuration = SessionConfiguration()
        configuration.academic_session = datetime.now().year - 2
        configuration.etranzact_enabled = True
        self.app['configuration'].addSessionConfiguration(configuration)
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.manage_path)
        #IWorkflowState(self.student).setState('started')
        super(EtranzactTestsApplicants, self).fill_correct_values()
        self.applicantscontainer.application_fee = 1000.0
        self.browser.getControl(name="form.nationality").value = ['NG']
        self.browser.getControl(name="transition").value = ['start']
        self.browser.getControl("Save").click()
        self.browser.getControl("Add online").click()
        self.assertMatches('...ticket created...',
                           self.browser.contents)
        self.payment = self.applicant.values()[0]
        self.payment_url = self.browser.url

    @external_test
    def test_applicant_etranzact_form(self):
        # Manager can access Etranzact form
        self.browser.getLink("Pay via eTranzact").click()
        self.assertTrue("Pay now" in self.browser.contents)
        # Means of testing end here.
        return


