import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import UnexpectedAlertPresentException

# New instance of the Chrome driver 
driver = webdriver.Chrome()

# Open the admin url
driver.get("http://localhost/itech/lrr/Admin.php")

def assign_ta(driver, course_name, ta_name):
    course_dropdown = driver.find_element('id', 'courseDropdown')
    course_dropdown.click()
    selected_course_option = WebDriverWait(driver, 1200).until(
        EC.element_to_be_clickable((By.XPATH, f"//option[text()='{course_name}']"))
    )
    selected_course_option.click()

    # Select the TA
    ta_dropdown = driver.find_element('id', 'taDropdown')
    ta_dropdown.click()

    # Check if ta_name is not null before selecting
    if ta_name:
        selected_ta_option = WebDriverWait(driver, 1200).until(
            EC.element_to_be_clickable((By.XPATH, f"//option[text()='{ta_name}']"))
        )
        selected_ta_option.click()

    # Click the Assign button
    assign_button = driver.find_element('id', 'assignButton')
    assign_button.click()

    # Use WebDriverWait for more reliable alert handling
    try:
        alert = WebDriverWait(driver, 1200).until(EC.alert_is_present())
        alert_text = alert.text
        alert.accept()
        return alert_text
    except UnexpectedAlertPresentException:
        return None

# Generate all combinations of courses and TAs
courses = ["Python", "computer", "testing"]  
tas = ["MPIANA", "KABWANGA", "mark"]  

@pytest.mark.parametrize("course_name, ta_name", [(course, ta) for course in courses for ta in tas])
def assign_ta_test(course_name, ta_name):
    alert_text = assign_ta(driver, course_name, ta_name)

    try:
        assert "Success" in alert_text or "Error" in alert_text
        result = "Passed"
    except AssertionError:
        result = "Failed"

    # Write the result to the text file
    with open('test_results.txt', 'a') as result_file:
        result_file.write(f"Course={course_name}, TA={ta_name}, Result={result}, Alert={alert_text}\n")

# Close the browser window
driver.quit()