import pytest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By


@pytest.fixture
def driver(request):
    wd = webdriver.Chrome()
    request.addfinalizer(wd.quit)
    return wd


def is_element_present(driver, *args):
    try:
        driver.find_element(*args)
        return True
    except NoSuchElementException:
        return False


def test_register_new_user(driver):
    # Login to admin
    driver.get("http://localhost/litecart/admin/")
    driver.find_element_by_xpath("//input[@name='username']").send_keys("admin")
    driver.find_element_by_xpath("//input[@name='password']").send_keys("admin")
    driver.find_element_by_xpath("//button[@name='login']").click()
    # Getting all links from main menu
    all_main_links = driver.find_elements_by_css_selector("#app->a")
    # Find length of list with links and starting a loop
    for i in range(len(all_main_links)):
        # Every loop find list with links
        all_main_links = driver.find_elements_by_css_selector("#app->a")
        # Click on link
        link = all_main_links[i]
        link.click()
        # Asserting presence of header
        is_element_present(driver, By.CSS_SELECTOR, "#content>h1")
        # Getting all links from submenu
        submenu_list = driver.find_elements_by_css_selector("#app->ul>li>a")
        if len(submenu_list) > 0:
            for j in range(len(submenu_list)):
                submenu_list = driver.find_elements_by_css_selector("#app->ul>li>a")
                submenu = submenu_list[j]
                submenu.click()
                is_element_present(driver, By.CSS_SELECTOR, "#content>h1")
