## $Id: helpers.py 14916 2017-11-30 09:10:38Z 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
##
"""General helper functions for the remita module in custom packages.
"""
import grok
from datetime import datetime
import httplib
import hashlib
import json

from zope.event import notify
from kofacustom.nigeria.interfaces import MessageFactory as _

def get_JSON_POST_response(
        merchantId, serviceTypeId, api_key, orderId,
        amount, responseurl, host, url, https, fullname, email, lineitems):
    hashargs = 	merchantId + serviceTypeId + orderId + str(amount) + responseurl + api_key
    hashvalue = hashlib.sha512(hashargs).hexdigest()
    headers={
        'Content-Type':'application/json; charset=utf-8',
    }
    if https:
        h = httplib.HTTPSConnection(host)
    else:
        h = httplib.HTTPConnection(host)
    data = {
            "merchantId":merchantId,
            "serviceTypeId":serviceTypeId,
            "totalAmount":amount,
            "hash":hashvalue,
            "payerName":fullname,
            "payerEmail":email,
            "orderId":orderId,
            "responseurl":responseurl,
            "lineItems":lineitems
            }
    try:
        h.request("POST", url, body=json.dumps(data), headers=headers)
        resp = h.getresponse()
    except:
        return {'error': 'Socket Error: Connection to Remita gateway refused.'}
    if resp.status!=200:
        return {'error': 'Connection Error (%s, %s)' % (resp.status, resp.reason)}
    jsonout = resp.read()
    try:
        parsed_json = json.loads(jsonout[6:-1])
    except ValueError:
        return {'error': 'No JSON response'}
    return parsed_json

def get_payment_status_via_rrr(merchantId, api_key, RRR, host, https):
    RRR = RRR.rstrip()
    hashargs = 	RRR + api_key + merchantId
    hashvalue = hashlib.sha512(hashargs).hexdigest()
    headers={
        'Content-Type':'application/json; charset=utf-8',
    }
    url = '/remita/ecomm/%s/%s/%s/status.reg' % (merchantId, RRR, hashvalue)
    if https:
        h = httplib.HTTPSConnection(host)
    else:
        h = httplib.HTTPConnection(host)
    try:
        h.request("GET", url, headers=headers)
    except:
        return {'error': 'Socket Error: Connection to Remita gateway refused.'}
    resp = h.getresponse()
    if resp.status!=200:
        return {'error': 'Connection error (%s, %s)' % (resp.status, resp.reason)}
    jsonout = resp.read()
    try:
        parsed_json = json.loads(jsonout)
    except ValueError:
        return {'error': 'No JSON response'}
    return parsed_json

def query_remita(payment, merchantId, api_key, RRR, host, https, verify):

    jr = get_payment_status_via_rrr(merchantId, api_key, RRR, host, https)
    error = jr.get('error')
    if error:
        msg = log = error
        return False, msg, log

    # A typical JSON response
    # {
    # u'orderId': u'3456346346',
    # u'status': u'021',
    # u'amount': 1000.0,
    # u'transactiontime': u'2017-07-31 11:17:24 AM',
    # u'message': u'Transaction Pending',
    # u'lineitems': [{u'status': u'021', u'lineItemsId': u'itemid1'},
    #                {u'status': u'021', u'lineItemsId': u'itemid2'}
    #               ],
    # u'RRR': u'280007640804'}

    payment.r_code = jr['status']
    payment.r_desc = jr['message']
    payment.r_amount_approved = jr['amount']
    payment.r_pay_reference = jr['RRR']
    payment.r_company = u'remita'
    if payment.r_code not in ('00', '01'):
        msg = _('Unsuccessful response: ${a}', mapping = {'a': payment.r_desc})
        log = 'unsuccessful response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, payment.r_desc)
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    if round(payment.r_amount_approved/10.0, 0) != round(
        payment.amount_auth/10.0, 0):
        msg = _('Response amount does not match.')
        log = 'wrong response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, str(jr))
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    orderId = jr.get('orderId', None)
    if orderId and orderId != payment.p_id:
        msg = _('Response order id does not match.')
        log = 'wrong response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, str(jr))
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    payment.p_state = 'paid'
    if not verify:
        payment.payment_date = datetime.utcnow()
    msg = _('Successful response received')
    log = 'valid response for %s payment %s: %s' % (
        payment.p_category, payment.p_id, str(jr))
    notify(grok.ObjectModifiedEvent(payment))
    return True, msg, log

def write_payments_log(id, payment):
    payment.logger.info(
        '%s,%s,%s,%s,%s,%s,%s,%s,,,' % (
        id, payment.p_id, payment.p_category,
        payment.amount_auth, payment.r_code,
        payment.provider_amt, payment.gateway_amt,
        payment.thirdparty_amt))