import os
import time
import logging

from django.test import TestCase, Client
from django.conf import settings
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import (
    WebDriverException, NoSuchElementException
)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from django.contrib.staticfiles.testing import StaticLiveServerTestCase

logger = logging.getLogger(__name__)


class CouponTests(StaticLiveServerTestCase):
    fixtures = ['products.json', 'accounts.json', 'coupons.json']

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.browser = WebDriver()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def login(self):
        self.browser.get('%s%s' % (self.live_server_url, '/accounts/login/'))
        username_input = self.browser.find_element_by_name("login")
        username_input.send_keys('john@example.com')
        password_input = self.browser.find_element_by_name("password")
        password_input.send_keys('Bf25XBdP4vdt2X9L')
        self.browser.find_element_by_xpath('//input[@value="Login"]').click()

    def test_driver_has_session(self):
        self.browser.get(self.live_server_url)
        session_id = self.browser.get_cookie('sessionid')
        self.assertTrue(session_id)

    def test_apply_coupon_to_order_for_non_registered_user(self):
        # Add item to cart
        self.browser.get(self.live_server_url + '/products/1/')
        self.browser.find_element_by_xpath(
            '//input[@value="Add to cart"]'
        ).click()
        self.assertEqual(
            self.browser.find_element_by_class_name('cart__count').text,
            '1'
        )

        # Add coupon code
        coupon_input = self.browser.find_element_by_id('id_code')
        coupon_input.send_keys('MAY2022')
        self.browser.find_element_by_xpath('//input[@value="Apply"]').click()
        self.browser.find_element_by_xpath(
            '//a[contains(text(), "Proceed to Checkout")]'
        ).click()

        # Add address
        self.assertEqual(
            self.browser.title,
            'Checkout | Port Townsend Roasting Co.'
        )
        full_name_input = self.browser.find_element_by_name("full_name")
        full_name_input.send_keys('Peter Templer')
        email_input = self.browser.find_element_by_id('id_email')
        email_input.send_keys('peter@example.com')
        street_address_1_input = self.browser.find_element_by_name(
            'street_address_1'
        )
        street_address_1_input.send_keys('1579 Talon Dr')
        city_input = self.browser.find_element_by_name('city')
        city_input.send_keys('Logan')
        state_select = select = Select(
            self.browser.find_element_by_name('state')
        )
        state_select.select_by_value('UT')
        postal_code_input = self.browser.find_element_by_name('postal_code')
        postal_code_input.send_keys('84321')
        self.browser.find_element_by_xpath(
            '//input[@value="Continue"]'
        ).click()

        self.assertEqual(
            self.browser.title,
            'Checkout | Port Townsend Roasting Co.'
        )

        # Check there is not an exception
        with self.assertRaises(NoSuchElementException):
            self.browser.find_element_by_css_selector(
                '.messages p'
            ).text

    def test_apply_used_coupon_to_order_returns_message(self):
        # Add item to cart
        self.browser.get(self.live_server_url + '/products/1/')
        self.browser.find_element_by_xpath(
            '//input[@value="Add to cart"]'
        ).click()
        self.assertEqual(
            self.browser.find_element_by_class_name('cart__count').text,
            '1'
        )

        # Add coupon code
        coupon_input = self.browser.find_element_by_id('id_code')
        coupon_input.send_keys('MAY2022')
        self.browser.find_element_by_xpath('//input[@value="Apply"]').click()
        self.browser.find_element_by_xpath(
            '//a[contains(text(), "Proceed to Checkout")]'
        ).click()

        # Add address
        self.assertEqual(
            self.browser.title,
            'Checkout | Port Townsend Roasting Co.'
        )
        full_name_input = self.browser.find_element_by_name("full_name")
        full_name_input.send_keys('John Doe')
        email_input = self.browser.find_element_by_id('id_email')
        email_input.send_keys('contact@nathanjchapman.com')
        street_address_1_input = self.browser.find_element_by_name(
            'street_address_1'
        )
        street_address_1_input.send_keys('1579 Talon Dr')
        city_input = self.browser.find_element_by_name('city')
        city_input.send_keys('Logan')
        state_select = select = Select(
            self.browser.find_element_by_name('state')
        )
        state_select.select_by_value('UT')
        postal_code_input = self.browser.find_element_by_name('postal_code')
        postal_code_input.send_keys('84321')
        self.browser.find_element_by_xpath(
            '//input[@value="Continue"]'
        ).click()

        self.assertEqual(
            self.browser.title,
            'Checkout | Port Townsend Roasting Co.'
        )

        message_text = self.browser.find_element_by_css_selector(
            '.messages p'
        ).text
        self.assertEqual(
            'Coupon already used.',
            message_text
        )
