import time
import os
import sys
import smtplib
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import mysql.connector

def getUser(email):
    cursor = connection.cursor()
    select_query = "SELECT id, remember_token FROM users WHERE email = (%s)"
    cursor.execute(select_query, (email,))
    result = cursor.fetchone()
    if result is not None:
        user = {
            'id':result[0],
            'token':result[1],
        }
        cursor.close()
        return user
    cursor.close()
    return result

def send_email(mailConfig, userEmail, userToken):
    message = MIMEMultipart()
    message["From"] = mailConfig['sender_email']
    message["To"] = userEmail
    message["Subject"] = 'Welcome to AS Express LLC.'
    html_content = f'''
    <html>
        <body>
            <p>Please confirm your email address by clicking the link below:</p>
            <p><a href="https://asexpresstms.com/confirmmail/{userToken['id']}/{userToken['token']}">Click here to verify your email</a></p>
            <p>-- OR -- </p>
            <p><a href="https://asexpresstms.com/confirmmail/{userToken['id']}/{userToken['token']}">https://asexpresstms.ts/confirmmail/{userToken['id']}/{userToken['token']}</a></p>
        </body>
    </html>
    '''
    message.attach(MIMEText(html_content, "html"))

    # Connect to the SMTP server and send the email
    with smtplib.SMTP(mailConfig['smtp_server'], mailConfig['smtp_port']) as server:
        server.starttls()
        server.login(mailConfig['smtp_username'], mailConfig['smtp_password'])
        server.sendmail(mailConfig['sender_email'], userEmail, message.as_string())

mailConfig = {
    'sender_email':"noreply@asexpresstms.com",
    'smtp_server':"smtp.ionos.com",
    'smtp_port':587,
    'smtp_username':"noreply@asexpresstms.com",
    'smtp_password':"Jfghxz&Hik",
}

db_config = {
    "host": "localhost",
    "user": "rsghihjbaoh",
    "password": "dD8X/p99JY1w",
    "database": "asexpresstms"
}
if len(sys.argv)>0:
    connection = mysql.connector.connect(**db_config)
    userToken = getUser(sys.argv[1])
    if userToken:
        try:
            send_email(mailConfig,sys.argv[1],userToken)
        except Exception as e:
            print('User did not founded.', end='')
            sys.exit()
        finally:
            print('Email was sent.', end='')
    else:
        print('User did not founded.', end='')
else:
    print('Error while sending email.', end='')
