import logging
from decimal import Decimal

from measurement.measures import Weight
from django.test import TestCase, Client, RequestFactory
from django.urls import reverse
from django.conf import settings
from django.contrib.sessions.middleware import SessionMiddleware
from paypalcheckoutsdk.orders import OrdersCreateRequest, OrdersCaptureRequest
from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment

from accounts.models import User, Address
from core.models import Product, ProductVariant, Order
from core import CoffeeGrind
from storefront.views import OrderCreateView
from storefront.cart import CartItem, Cart
from storefront.payments import CreateOrder

from . import RequestFaker

logger = logging.getLogger(__name__)


class CreateOrderTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.product = Product.objects.create(
            name='Decaf',
            subtitle='Medium Roast',
            description='Coffee',
            checkout_limit=10,
            visible_in_listings=True
        )
        cls.variant = ProductVariant.objects.create(
            product=cls.product,
            name='16 oz',
            sku='234987',
            price=13.4,
            weight=Weight(oz=16)
        )

    def setUp(self):
        self.client = Client()

    def test_build_request_body(self):
        product_list_url = reverse('storefront:product-list')
        response = self.client.get(product_list_url, follow=True)
        request = response.wsgi_request

        cart = Cart(request)
        cart.add_item(
            CartItem({
                'variant_pk': self.variant.pk,
                'options': {'Grind': 'Whole Beans'},
                'quantity': 1
            })
        )
        cart.add_item(
            CartItem({
                'variant_pk': self.variant.pk,
                'options': {'Grind': 'Percolator'},
                'quantity': 2
            })
        )
        params = {
            'items': cart,
            'total_price': '45.20',
            'item_total': '40.20',
            'discount': '0',
            'shipping_price': '5.00',
            'tax_total': '0',
            'shipping_method': 'US POSTAL SERVICE',
            'shipping_address': {
                'address_line_1': '1504 N 230 E',
                'address_line_2': '',
                'admin_area_2': 'North Logan',
                'admin_area_1': 'UT',
                'postal_code': '84341',
                'country_code': 'US',
            },
        }
        request_body = CreateOrder().build_request_body(params)
        self.assertDictEqual(RequestFaker.REQUEST_BODY, request_body)
