import time
import logging
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

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Path to the geckodriver (ensure this path is correct)
driver_path = "/usr/local/bin/geckodriver"  # Update this path if geckodriver is elsewhere

def initialize_driver():
    """ Initializes and returns the Firefox WebDriver. """
    return webdriver.Firefox(executable_path=driver_path)

def login(driver):
    """ Logs into the attendance portal. """
    url = "http://iattendance.com:8004"  # Replace with your actual login URL
    driver.get(url)

    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')

    # Hardcoded credentials; consider using environment variables for security
    username = 'fhill@mail.com'  # Your email address
    password = 'password@1'       # Your password

    username_field.send_keys(username)
    password_field.send_keys(password)
    password_field.send_keys(Keys.RETURN)

def navigate_to_dashboard(driver):
    """ Navigates to the attendance dashboard. """
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, "Dashboard")))
    driver.find_element(By.LINK_TEXT, "Dashboard").click()

def check_attendance(driver):
    """ Checks if today's attendance is already marked. """
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'zero_config')))
    
    today_date = datetime.now().strftime("%d %b, %Y")
    logging.info(f"Today's Date: {today_date}")
    table_rows = driver.find_elements(By.XPATH, "//table[@id='zero_config']/tbody/tr")

    attendance_present = False  
    for row in table_rows:
        date_text = row.find_element(By.XPATH, ".//td[1]").text.strip()

        logging.info(f"Found Date: {date_text}")
        if date_text == today_date:
            check_in_time = row.find_element(By.XPATH, ".//td[2]").text.strip()
            status_text = row.find_element(By.XPATH, ".//td[5]").text.strip()

            logging.info(f"Check-In Time for {date_text}: {check_in_time}")
            logging.info(f"Status for {date_text}: {status_text}")

            if status_text.lower() == "present":
                logging.info(f"Today's attendance is already marked as '{status_text}' at {check_in_time}. No action required.")
                attendance_present = True
                break

    return attendance_present  # Return True if attendance is marked, otherwise False.

def mark_attendance(driver):
    """ Marks attendance if not already present. """
    if not check_attendance(driver):  # Check if already present
        mark_attendance_button = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "markAttendanceButton"))
        )
        mark_attendance_button.click()  # Click to mark attendance
        logging.info("Attendance marked.")
        return True  # Return True when attendance is successfully marked
    return False  # Return False if attendance is already marked.

def wait_until_target_time(target_hour, target_minute):
    """ Waits until the specified hour and minute. """
    while True:
        now = datetime.now()
        if now.hour == target_hour and now.minute == target_minute:
            logging.info("Time to mark attendance.")
            break
        logging.info(f"Current time is {now.hour}:{now.minute}. Waiting...")
        time.sleep(30)  # Check every 30 seconds

def main():
    # Define the target time to mark attendance (e.g., 6:00 AM or 18:00 for 6 PM)
    target_hour = 6   # Use 18 for 6 PM
    target_minute = 0

    wait_until_target_time(target_hour, target_minute)

    driver = initialize_driver()
    try:
        login(driver)
        navigate_to_dashboard(driver)
        attendance_marked = mark_attendance(driver)
        if attendance_marked:
            logging.info("Attendance for today has been marked successfully.")
        else:
            logging.info("Attendance was already marked today.")
    finally:
        driver.quit()  # Ensure the driver quits, even if an error occurs

if __name__ == "__main__":
    main()