
from email.mime.text import MIMEText
import os
from smtplib import SMTP_SSL as SMTP

from dotenv import find_dotenv, load_dotenv
#load_dotenv(find_dotenv())



class SendingEmails:
    def sendingEmails(self, dto):
        
        adminName = dto["adminName"]
        title = dto["title"]
        status = dto["status"]
        note = dto["note"]
        verb = 'approvata' if status["id"] == 3 else 'rifiutata'
        reason = f'Motivo del rifiuto: {note}.' if status["id"] == 4 else ''

        employee = dto["author"]

        smtp_server = os.getenv("SMTP_SERVER")
        smtp_port = 465  # (587  TLS, 465  SSL)
        smtp_username = os.getenv("SMTP_USERNAME")
        smtp_password = os.getenv("SMTP_PASSWORD")
        sender_email = os.getenv("SMTP_SENDER_EMAIL")

        receiver_email = employee["mail"]

        body = f'''
        Gentile {employee["givenName"]} {employee["surname"]}, <br><br>

        la tua nota spese "{title}" è stata {verb}. {reason}<br><br>
        
        Cordiali saluti,<br>
        {adminName}'''

        smtp = SMTP(smtp_server, smtp_port)
        try:
            # Create msg obj
            msg = MIMEText(body, 'html')
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = f'Nota spese "{title}"'
            msg.add_header('Reply-To', receiver_email)


            smtp.login(smtp_username, smtp_password)
            
            smtp.sendmail(sender_email, receiver_email, msg.as_string())
            return True

            
        except Exception as e:
            #print(f'Error: {str(e)}')
            return False
            
        finally:
            smtp.quit() 
