## $Id: browser.py 14759 2017-08-03 09:09:54Z 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 grok
import hashlib
from datetime import datetime, timedelta
from zope.component import getUtility
from zope.security import checkPermission
from waeup.kofa.interfaces import IKofaUtils
from waeup.kofa.utils.helpers import to_timezone
from waeup.kofa.browser.layout import UtilityView, KofaPage
from waeup.kofa.browser.viewlets import ManageActionButton
from waeup.kofa.applicants.browser import OnlinePaymentDisplayFormPage as OPDPApplicant
from kofacustom.nigeria.etranzact.helpers import (write_payments_log)
from kofacustom.nigeria.payments.interfaces import INigeriaOnlinePayment
from kofacustom.nigeria.applicants.interfaces import INigeriaApplicantOnlinePayment
from kofacustom.nigeria.interfaces import MessageFactory as _

from kofacustom.nigeria.etranzact.tests import (
    TERMINAL_ID, HOST, HTTPS, SECRET_KEY, LOGO_URL)

grok.templatedir('browser_templates')

def module_activated(session):
    try:
        return getattr(grok.getSite()['configuration'][str(session)],
            'etranzact_enabled', False)
    except KeyError:
        return False

# Buttons

class EtranzactActionButtonApplicant(ManageActionButton):
    grok.order(1)
    grok.context(INigeriaOnlinePayment)
    grok.view(OPDPApplicant)
    grok.require('waeup.payApplicant')
    icon = 'actionicon_pay.png'
    text = _('Pay via eTranzact')
    target = 'goto_etranzact'

    @property
    def target_url(self):
        if not module_activated(self.context.__parent__.__parent__.year):
            return ''
        if self.context.p_state != 'unpaid':
            return ''
        return self.view.url(self.view.context, self.target)

# Forwarding pages

class EtranzactPageApplicant(KofaPage):
    """ View which sends a POST request to the eTranzact payment gateway.
    """
    grok.context(INigeriaApplicantOnlinePayment)
    grok.name('goto_etranzact')
    grok.template('goto_etranzact')
    grok.require('waeup.payApplicant')
    label = _('Pay via eTranzact')
    submit_button = _('Pay now')

    host = HOST
    https = HTTPS
    secret_key = SECRET_KEY
    terminal_id = TERMINAL_ID
    logo_url = LOGO_URL

    @property
    def action(self):
        if self.https:
            return 'https://' + self.host + '/webconnect/v3/caller.jsp'
        return 'http://' + self.host + '/webconnect/v3/caller.jsp'

    def init_update(self):
        if self.context.p_state == 'paid':
            return _("Payment ticket can't be re-sent to eTranzact.")
        now = datetime.utcnow()
        if self.context.creation_date.tzinfo is not None:
            # That's bad. Please store timezone-naive datetimes only!
            now = self.context.creation_date.tzinfo.localize(now)
        time_delta = now - self.context.creation_date
        if time_delta.days > 7:
            return _("This payment ticket is too old. Please create a new ticket.")
        self.responseurl = self.url(self.context, 'query_etranzact')
        # Already now it becomes a eTranzact payment
        self.context.r_company = u'etranzact'
        hashargs = 	self.amount + self.terminal_id+self.transaction_id \
            + self.responseurl + self.secret_key
        self.hashvalue = hashlib.md5(hashargs).hexdigest()
        self.customer = self.context.__parent__
        return

    def update(self):
        if not module_activated(self.context.__parent__.__parent__.year):
            return
        self.transaction_id = self.context.p_id
        self.amount = "%.1f" % self.context.amount_auth
        error = self.init_update()
        if error:
            self.flash(error, type='danger')
            self.redirect(self.url(self.context, '@@index'))
            return
        return
