import logging
from decimal import Decimal

from django.test import TestCase, Client, RequestFactory
from django.urls import reverse
from django.conf import settings
from measurement.measures import Weight
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

logger = logging.getLogger(__name__)


class CartTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.customer = User.objects.create_user(
            username='petertempler',
            email='peter@testing.com',
            password='peterspassword321'
        )
        cls.product = Product.objects.create(
            name='Dante\'s Tornado',
            description='Coffee',
            sku='23987',
            price=13.4,
            weight=Weight(oz=16),
            visible_in_listings=True
        )
        cls.order = Order.objects.create(
            customer=cls.customer,
            total_net_amount=13.4
        )

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

        self.client.force_login(self.customer)
        self.client.session['shipping_address'] = {
            'first_name': 'Nathan',
            'last_name': 'Chapman',
            'email': 'contact@nathanjchapman.com',
            'street_address_1': '1504 N 230 E',
            'street_address_2': '',
            'city': 'North Logan',
            'state': 'UT',
            'postal_code': '84341'
        }

    def test_cart_item_variations(self):
        cart_detail_url = reverse('storefront:cart-detail')
        response = self.client.get(cart_detail_url, follow=True)
        logger.debug(response.context['messages'])
        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=1,
            grind=CoffeeGrind.ESPRESSO,
            update_quantity=False
        )
        for item in cart.cart.values():
            self.assertTrue('variations' in item, item)

    def test_add_item_to_cart(self):
        cart_detail_url = reverse('storefront:cart-detail')
        response = self.client.get(cart_detail_url)
        request = response.wsgi_request
        cart = Cart(request)

        cart = Cart(request)
        cart.add(
            request,
            product=self.product,
            quantity=1,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )

        self.assertEqual(
            cart.cart[f'{self.product.id}']['variations'][CoffeeGrind.WHOLE]['quantity'],
            1
        )
        self.assertEqual(len(cart), 1)
        self.assertEqual(sum(cart.get_item_prices()), Decimal('13.4'))
        self.assertEqual(cart.get_total_price(), Decimal('13.4'))
        cart.add(
            request,
            product=self.product,
            quantity=1,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )
        self.assertEqual(
            cart.cart[f'{self.product.id}']['variations'][CoffeeGrind.WHOLE]['quantity'],
            2
        )
        self.assertEqual(len(cart), 2)

        cart.add(
            request,
            product=self.product,
            quantity=3,
            grind=CoffeeGrind.ESPRESSO,
            update_quantity=False
        )
        self.assertEqual(
            cart.cart[f'{self.product.id}']['variations'][CoffeeGrind.ESPRESSO]['quantity'],
            3
        )
        self.assertEqual(len(cart), 5)
        self.assertEqual(cart.get_total_price(), Decimal('67'))

    def test_update_cart_item_quantity(self):
        cart_detail_url = reverse('storefront:cart-detail')
        response = self.client.get(cart_detail_url)
        request = response.wsgi_request
        cart = Cart(request)

        cart = Cart(request)
        cart.add(
            request,
            product=self.product,
            quantity=3,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )
        self.assertEqual(
            cart.cart[f'{self.product.id}']['variations'][CoffeeGrind.WHOLE]['quantity'],
            3
        )

        cart.add(
            request,
            product=self.product,
            quantity=1,
            grind=CoffeeGrind.WHOLE,
            update_quantity=True
        )
        self.assertEqual(
            cart.cart[f'{self.product.id}']['variations'][CoffeeGrind.WHOLE]['quantity'],
            1
        )

    def test_cart_remove_item(self):
        cart_detail_url = reverse('storefront:cart-detail')
        response = self.client.get(cart_detail_url)
        request = response.wsgi_request
        cart = Cart(request)

        cart = Cart(request)
        cart.add(
            request,
            product=self.product,
            quantity=3,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )
        self.assertEqual(len(cart), 3)
        cart.remove(self.product, CoffeeGrind.WHOLE)
        self.assertEqual(len(cart), 0)

    def test_cart_get_total_weight(self):
        cart_detail_url = reverse('storefront:cart-detail')
        response = self.client.get(cart_detail_url)
        request = response.wsgi_request
        cart = Cart(request)

        cart = Cart(request)
        cart.add(
            request,
            product=self.product,
            quantity=3,
            grind=CoffeeGrind.WHOLE,
            update_quantity=False
        )
        self.assertEqual(cart.get_total_weight(), Decimal(48))
