import pytest
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By

from pages.ui.login import KmartLoginPage
from pages.ui.navigate import KmartChairPage
from pages.ui.search import KmartSearchPage


@pytest.fixture
def browser():
    # Initialize ChromeDriver
    driver = Chrome()
    # Wait implicitly for elements to be ready before attempting interactions
    driver.implicitly_wait(10)

    # Return the driver object at the end of setup
    yield driver

    # For cleanup, quit the driver
    driver.quit()


def test_kmart_web(browser):
    # Set up test case data, Can be read from JSON file
    USERNAME = 'kmartuser95@gmail.com'
    PASSWORD = 'Test@1234'
    SEARCH_PHRASE = 'chair'
    PRODUCT_ID = '3380843'

    # Login to kmart
    login_page = KmartLoginPage(browser)
    login_page.load()
    login_page.login(USERNAME, PASSWORD)

    signout_link = login_page.browser.find_elements(By.ID, 'SignOutLink')
    assert len(signout_link) > 0, "Login failed"

    if len(signout_link) == 0:
        return

    # Search the given item
    search_page = KmartSearchPage(browser)
    search_page.search(SEARCH_PHRASE)
    search_items = search_page.browser.find_elements(By.XPATH, "//div[@id='resultcontent']")

    assert len(search_items) > 0, "No products found with given search string"

    if len(search_items) == 0:
        return

    # Navigate to chair page of a given product_id
    chair_page = KmartChairPage(browser)
    chair_page.navigate(PRODUCT_ID)

    chair_item = chair_page.browser.find_elements(By.XPATH, "//div[@class='product-details-desc']")

    assert len(chair_item) > 0, "Unable to navigate to product page"



