from selenium import webdriver
from selenium.webdriver.common.by import By
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.firefox.options import Options
import smtplib
import time
from dotenv import load_dotenv
import os
import json


# Load environment variables from .env file
load_dotenv()

# Email Configuration from environment variables
SMTP_SERVER = os.getenv("SMTP_SERVER")
SMTP_PORT = int(os.getenv("SMTP_PORT"))
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")

DAYS_BEFORE = int(os.getenv("DAYS_BEFORE"))

def check_date(due_date, recipient_email):
    today = datetime.now()
    if today <= due_date <= today + timedelta(days=DAYS_BEFORE):
        print(f"Reminder: Book is due on {due_date}")

        # Send an email reminder
        subject = "Stadtbibliothek Radebeul - Buch bald fällig"
        body = f"Ein Buch muss am {due_date.strftime('%d.%m.%Y')} zurückgegeben werden. Bitte zurückgeben um Gebühren zu vermeiden."

        # Set up email
        msg = MIMEMultipart()
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = recipient_email
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        # Connect to SMTP server and send email
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # Secure the connection
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            server.send_message(msg)
        print(f"Email sent to {recipient_email}")

def check_books(user, pw, recipient_email):
    options = Options()
    options.add_argument("--headless")
    driver = webdriver.Firefox(options=options)
    try:
        # Navigate to the login page
        driver.get("https://webserver.sv-radebeul.de/Mediensuche-Konto/Mein-Konto")

        # Wait for the page to load
        wait = WebDriverWait(driver, 10)

        # Locate username and password fields
        username_field = driver.find_element(By.ID, "dnn_ctr355_Login_Login_COP_txtUsername")
        password_field = driver.find_element(By.ID, "dnn_ctr355_Login_Login_COP_txtPassword")

        # Enter login credentials
        username_field.send_keys(user)
        password_field.send_keys(pw)

        # Click login button
        login_button = driver.find_element(By.ID, "dnn_ctr355_Login_Login_COP_cmdLogin")
        login_button.click()

        # Wait for login to complete
        time.sleep(5)

        # Check if login was successful
        if "Mein Konto" in driver.page_source:
            print(f"Login successful for {user}!")
            # Locate the table containing the rows
            table = driver.find_element(By.ID, "dnn_ctr423_MainView_tpnlLoans_ucLoansView_grdViewLoans")
            table_rows = table.find_elements(By.XPATH, "./tbody/tr")

            # Loop through each row and extract the "Aktuelle Frist" date
            for row in table_rows:
                try:
                    # Locate the "Aktuelle Frist" column in the current row
                    due_date = row.find_element(By.XPATH, ".//td[span[contains(text(), 'Aktuelle Frist:')]]/span[2]")
                    print(f"Aktuelle Frist for {user}: {due_date.text}")
                    check_date(datetime.strptime(due_date.text, "%d.%m.%Y"), recipient_email)
                except Exception as e:
                    print(f"Could not extract 'Aktuelle Frist' date for a row: {e}")
        else:
            print(f"Login failed for {user}. Please check the credentials or the page structure.")
    finally:
        # Close the browser
        driver.quit()

if __name__ == '__main__':
    # Load user credentials from JSON file
    with open("users.json", "r") as file:
        users = json.load(file)

    # Iterate over all users
    for user_data in users:
        username = user_data["username"]
        password = user_data["password"]
        recipient_email = user_data["recipient_email"]
        check_books(username, password, recipient_email)