# emailClient.py
import smtplib
import imaplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import threading

class EmailClient:
    def __init__(self):
        self.server_ip = "192.168.120.103"
        self.ports = {
            "SMTP": 25,
            "SMTP-S": 465,
            "SMTP-SUBMISSION": 587,
            "IMAP": 143,
            "IMAP-S": 993
        }

    def enviar_correo(self, email_user, password, destinatario, asunto, mensaje):
        def enviar():
            try:
                with smtplib.SMTP(self.server_ip, self.ports["SMTP"]) as smtp:
                    smtp.login(email_user, password)
                    msg = MIMEMultipart()
                    msg["From"] = email_user
                    msg["To"] = destinatario
                    msg["Subject"] = asunto
                    msg.attach(MIMEText(mensaje, "plain"))
                    smtp.sendmail(email_user, destinatario, msg.as_string())
                    print("Correo enviado correctamente.")
            except Exception as e:
                print(f"Error al enviar el correo: {e}")

        thread = threading.Thread(target=enviar)
        thread.start()

    def recibir_correos(self, email_user, password, text_widget):
        def recibir():
            try:
                with imaplib.IMAP4_SSL(self.server_ip, self.ports["IMAP-S"]) as mail:
                    mail.login(email_user, password)
                    mail.select("inbox")
                    status, mensajes_no_leidos = mail.search(None, 'UNSEEN')
                    no_leidos = mensajes_no_leidos[0].split()

                    text_widget.delete("1.0", "end")
                    text_widget.insert("end", f"Tienes {len(no_leidos)} correos no leídos.\n")
                    
                    for num in no_leidos:
                        status, data = mail.fetch(num, '(RFC822)')
                        mensaje = email.message_from_bytes(data[0][1])
                        text_widget.insert("end", f"[NO LEÍDO] {mensaje['Subject']}\n")
                        mail.store(num, '+FLAGS', '\\Seen')
            except Exception as e:
                text_widget.insert("end", f"Error al recibir correos: {e}\n")

        thread = threading.Thread(target=recibir)
        thread.start()
