import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def mark_attendance():
    driver_path = "/usr/local/bin/geckodriver"  # Path to geckodriver
    driver = webdriver.Firefox(executable_path=driver_path)

    try:
        url = "http://iattendance.com:8004"  # Change to your actual login URL
        driver.get(url)

        # Wait for the email input and password fields
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'email')))
        username_field = driver.find_element(By.ID, 'email')
        password_field = driver.find_element(By.NAME, 'password')

        # Enter credentials
        username_field.send_keys('fhill@mail.com')  # Replace with your actual email
        password_field.send_keys('password@1')       # Replace with your actual password
        password_field.send_keys(Keys.RETURN)        # Submit the form

        # Wait for the dashboard link and navigate there
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, "Dashboard")))
        dashboard_link = driver.find_element(By.LINK_TEXT, "Dashboard")
        dashboard_link.click()

        # Wait for the attendance table to be visible
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'zero_config')))

        # Get today's date from the local machine (automatically fetched)
        local_today_date = datetime.now().strftime("%d %b, %Y")  # e.g., "02 Feb, 2025"

        # Check the attendance table for today's date
        table_rows = driver.find_elements(By.XPATH, "//table[@id='zero_config']/tbody/tr")
        
        attendance_present = False
        
        for row in table_rows:
            date_cell = row.find_element(By.XPATH, ".//td[1]")  # Get the first cell (Date)
            date_text = date_cell.text.strip()  # Extract the text and strip whitespace

            # Compare the attendance portal date with the local machine date
            if date_text == local_today_date:
                attendance_present = True  # Mark that attendance is present
                print(f"Attendance for {local_today_date} is already marked. No action required.")
                break  # Exit loop if date is found

        # If today's date is not present and local machine time is between 06:00 and 06:15
        current_time = datetime.now().strftime("%H:%M")  # Local time in 24-hour format
        if not attendance_present and "06:00" <= current_time <= "06:15":
            mark_attendance_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.ID, "markAttendanceButton"))
            )
            mark_attendance_button.click()
            print(f"Attendance for {local_today_date} has been marked at {current_time}.")

    finally:
        driver.quit()

# Main loop to keep checking for attendance marking
while True:
    current_hour = datetime.now().strftime("%H:%M")
    if "06:00" <= current_hour <= "06:15":
        mark_attendance()  # Attempt to mark attendance
    else:
        print("Waiting for the right time to mark attendance...")
    
    # Wait for a minute before checking again
    time.sleep(60)