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, Order
from core import CoffeeGrind
from storefront.views import OrderCreateView
from storefront.cart import 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',
            description='Coffee',
            sku='23987',
            price=Decimal('13.40'),
            weight=Weight(oz=16),
            visible_in_listings=True
        )

    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(
            request,
            product=self.product,
            quantity=1,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )
        cart.add(
            request,
            product=self.product,
            quantity=2,
            grind=CoffeeGrind.PERCOLATOR,
            update_quantity=False
        )
        params = {
            'items': cart,
            'total_price': '13.40',
            'item_total': '13.40',
            'discount': '0',
            'shipping_price': '0.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)
