import re
import smtplib
import Visure

# Send email when entering a comment or replying to a comment

MAIL_SERVER     = "smtp.gmail.com"
MAIL_PORT       = 587
SENDER_ADDRESS  = "SENDER@YOURDOMAIN.COM"
SENDER_PASSWORD = "YOUR_PASSWORD"
PROJECT         = "Evaluation SEP"
SPECIFICATION   = "Product Requirements"

regex = re.compile(r"([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\"([]!#-[^-~ \t]|(\\[\t -~]))+\")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])")

def is_valid_mail_address(email):
    return re.fullmatch(regex, email)

def send_email(bl, subject, recipient, text_body):
    # Sends an email

    try:
        # The bl.Trace_INFO option will ouput a given string in the log file of the server, either for debuggin purposes, or for logging
        # As as example, if uncommented, the following line would print "Start of the script" in the server's log file: 
        #bl.Trace_INFO("Start of script")
        # Import the email modules we'll need
        from email.mime.text import MIMEText

        # Create a text/plain message
        msg = MIMEText(text_body)

        msg['Subject'] = subject
        msg['From'] = SENDER_ADDRESS
        msg['To'] = recipient

        # Send the message via our own SMTP server, but don't include the envelope header
        session = smtplib.SMTP(MAIL_SERVER, MAIL_PORT)

        # Enable security
        session.starttls()

        # Login
        session.login(SENDER_ADDRESS, SENDER_PASSWORD)

        # Send mail
        session.sendmail(SENDER_ADDRESS, [recipient], msg.as_string())

        session.quit()

        #bl.Trace_INFO("Mail sent")

        return True

    except Exception as e:
        bl.Trace_ERROR(str(e))
        return False

def Visure_afterCreateCommentThread(bl, lCommentID, lElementID, strComment):
    try:
        # The project
        if PROJECT == bl.GetProjectName() :
            # The item
            item = bl.item(lElementID)

            # The specification
            specification = bl.specification(SPECIFICATION)

            # Check if the element belongs to the specification
            if specification.containsItem(lElementID) :
                # The item owner
                owner = bl.user(item.creation_user_id)

                # Mail address
                mail_address = fvalera@visuresolutions.com #owner.mail

                # Send the mail
                if is_valid_mail_address(mail_address) :
                    send_email(bl, "Visure Requirements notification", mail_address, "A new comment thread has been created on item '{}'".format(item.code))

        return True

    except Exception as e:
        #bl.Trace_ERROR(str(e))
        return True

def Visure_afterReplyCommentThread(bl, lCommentID, lThreadID, lElementID, strComment):
    try:
        # The project
        if PROJECT == bl.GetProjectName() :
            # The item
            item = bl.item(lElementID)

            # The specification
            specification = bl.specification(SPECIFICATION)

            # Check if the element belongs to the specification
            if specification.containsItem(lElementID) :
                # The item owner
                owner = bl.user(item.creation_user_id)

                # Mail address
                mail_address = owner.mail

                # Send the mail
                if is_valid_mail_address(mail_address) :
                    send_email(bl, "Visure Requirements notification", mail_address, "A new comment reply has been created on item '{}'".format(item.code))

        return True

    except Exception as e:
        #bl.Trace_ERROR(str(e))
        return True
