# coding=utf-8
from __future__ import unicode_literals

import tg
import paypalrestsdk
import datetime

def configure_paypal(mode, client_id, client_secret):
    paypalrestsdk.configure({
    "mode": mode,
    "client_id": client_id,
    "client_secret": client_secret})


def pay(cart, redirection_url, cancel_url):
    raw_items = [v for k, v in cart.items.iteritems()]
    items = []
    for item in raw_items:
        item_name = item.name.get(tg.translator.preferred_language, item.name.get(tg.config.lang))
        item_variety = item.variety.get(tg.translator.preferred_language, item.variety.get(tg.config.lang))
        item = {"name": "%s, %s" % (item_name, item_variety),
                "sku": item.sku,
                "price": item.price,
                "currency": "EUR",
                "quantity": item.qty}
        items.append(item)

    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url": redirection_url,
            "cancel_url": cancel_url
        },
        "transactions": [{"item_list": {"items": items},
                          "amount": {
                              "total": "%0.2f" % (cart.total + cart.order_info.shipping_charges),
                              "currency": "EUR",
                              "details": {
                                  "shipping": "%0.2f" % cart.order_info.shipping_charges,
                                  "subtotal": "%0.2f" % cart.subtotal,
                                  "tax":   "%0.2f" % cart.tax
                              }
                          },
                          }]
    })

    if payment.create():
        cart.order_info.payment = {'backend': 'paypal',
                                   'id': payment.id,
                                   'date': datetime.datetime.utcnow()}

        for link in payment.links:
            if link.rel == "approval_url":
                return link.href
    else:
        return cancel_url


def confirm(cart, redirection, data):
    payerId = data['PayerID']
    return tg.url(redirection, qualified=True, params={'payer_id': payerId})


def execute(cart, data):
    paymentId = cart.order_info.payment['id']
    payment = paypalrestsdk.Payment.find(paymentId)
    result = payment.execute(data)
    payer_info = dict()
    if result:
        payer_info['first_name'] = payment.payer.payer_info.first_name
        payer_info['last_name'] = payment.payer.payer_info.last_name
        payer_info['email'] = payment.payer.payer_info.email

    return dict(result=result, payer_info=payer_info)


@@ -847,16 +847,535 @@
 (item)%0A%0A
+    total_discount = 0%0A    for discount in cart.order_info%5B'details'%5D.get('discounts', %7B%7D).values():%0A        if discount%5B'type'%5D == 'percentage':%0A            qty = -(discount%5B'qty'%5D/100.0) * cart.total%0A            qty%0A        else:%0A            #todo: other kind of discounts%0A            qty = 0%0A        total_discount += qty%0A        items.append(%7B%0A            %22name%22: discount%5B'description'%5D,%0A            %22price%22: qty,%0A            %22sku%22: 'DISCOUNT',%0A            %22currency%22: %22EUR%22,%0A            %22quantity%22: 1%0A        %7D)%0A%0A
     paym
@@ -1404,16 +1404,16 @@
 yment(%7B%0A
-
         
@@ -1807,16 +1807,33 @@
 _charges
+ + total_discount
 ),%0A     
@@ -2061,24 +2061,25 @@
 : %22%250.2f%22 %25 
+(
 cart.subtota
@@ -2079,16 +2079,32 @@
 subtotal
++total_discount)
 ,%0A      
@@ -2574,16 +2574,16 @@
 nk.href%0A
-
     else
@@ -2576,32 +2576,60 @@
 .href%0A    else:%0A
+        print payment.error%0A
         return c

handle discounts in paypal