#!/usr/bin/env python3
import time
import os
import sys
import glob
import mysql.connector
import smtplib
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def getActiveDrivers():
    connection = mysql.connector.connect(**db_config)
    cursor = connection.cursor()
    select_query = "SELECT id,firstname,lastname,email FROM users WHERE active = 1 AND role='driver'"
    cursor.execute(select_query)
    drivers = cursor.fetchall()
    cursor.close()
    connection.close()
    return drivers

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 writingLog(progressbar, message, pid, parentDir):
    pylog = open(parentDir+'/public/pylogs/driversemails.log', 'w')
    pylog.write(str(progressbar)+'|'+str(message)+'..|'+str(pid))
    pylog.close()

def send_email(mailConfig, driver, attachments=[]):
    message = MIMEMultipart()
    message["From"] = mailConfig['sender_email']
    message["To"] = driver[3]
    message["Subject"] = 'Urgent! Update your documents!!'
    message.attach(MIMEText('Hello, '+str(driver[1])+' '+str(driver[2])+'!\nPlease download and print all new documents as soon as possible.', "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'], driver[3], 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'
currentPID = os.getpid()
drivers = getActiveDrivers()
step = int(80 / len(drivers))
progressbar = 20

if drivers:
    for driver in drivers:
        attachments = getFiles(parentDir+'/public/driversdocs/'+str(driver[0]))
        try:
            send_email(mailConfig,driver,attachments)
            writingLog(progressbar, 'Emailing driver id:' + str(driver[0]) + '..', currentPID, parentDir)
        except Exception as e:
            writingLog(progressbar, 'Emailing to this driver id:'+str(driver[0])+' denied.', currentPID, parentDir)
        progressbar = progressbar + step
        time.sleep(2)

time.sleep(5)
writingLog(0, 'done..', 'x', parentDir)
