#!/usr/bin/env python3
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

def getFiles(folder):
    files = [os.path.abspath(os.path.join(folder, f)) for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
    return files

def send_email(mailConfig, userEmail, attachments=[]):
    message = MIMEMultipart()
    message["From"] = mailConfig['sender_email']
    message["To"] = userEmail
    message["Subject"] = 'AS Express LLC. Statement Mail'
    message.attach(MIMEText('This statement was generated by TMS, please inform us if you have any missing loads in this file.', "plain"))

    # Attach files
    for attachment_path in attachments:
        attachment_filename = os.path.basename(attachment_path)
        with open(attachment_path, "rb") as attachment_file:
            part = MIMEApplication(attachment_file.read(), Name=attachment_path)
            part["Content-Disposition"] = f'attachment; filename="{attachment_filename}"'
            message.attach(part)

    # 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": "truckerbill"
}

parentDir = '/var/www/html/tms'
pass1 = pass2 = 0
emailPattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')

if len(sys.argv)>1:
    userId = sys.argv[1]
    userEmail = sys.argv[2]
    if emailPattern.match(userEmail):
        attachments = getFiles(parentDir + '/public/statementsfile/' + str(userId))
        try:
            send_email(mailConfig,userEmail,attachments)
        except Exception as e:
            print(e)
            # print('error3'+{e}, end='')
            sys.exit()
        finally:
            print('sent', end='')
    else:
        print('error1', end='')
else:
    print('error2', end='')
