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, Coupon
from core import CoffeeGrind
from storefront.forms import AddressForm, OrderCreateForm
from storefront.views import OrderCreateView, CheckoutAddressView
from storefront.cart import Cart

logger = logging.getLogger(__name__)


class CheckoutAddressViewTests(TestCase):
    def setUp(self):
        self.client = Client()

    def test_view_uses_correct_template(self):
        response = self.client.get(reverse('storefront:checkout-address'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'storefront/checkout_address.html')

    def test_view_has_correct_form(self):
        response = self.client.get(reverse('storefront:checkout-address'))
        self.assertTrue(response.context['form'])
        self.assertTrue(isinstance(response.context['form'], AddressForm))


class OrderCreateViewTests(TestCase):
    fixtures = ['accounts.json', 'coupons.json']

    @classmethod
    def setUpTestData(cls):
        cls.customer = User.objects.get(pk=1)
        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()

    def test_used_coupon_creates_error_on_checkout(self):
        session = self.client.session
        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'
        }
        session['coupon_code'] = 'MAY2022'
        session.save()

        response = self.client.get(
            reverse('storefront:order-create'), follow=True
        )
        self.assertTrue(self.client.session.get('shipping_address'))
        self.assertTemplateUsed(response, 'storefront/order_form.html')
        self.assertContains(response, 'Coupon already used', status_code=200)
