#!/usr/bin/env python3
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Inches, Pt
from datetime import date
import time
import os
import mysql.connector
import sys
import json
import subprocess

db_config = {
    "host": "localhost",
    "user": "rsghihjbaoh",
    "password": "dD8X/p99JY1w",
    "database": "truckerbill"
}

def passengerDoc(parentDir,carrier,passenger):
    today = date.today()
    datetoday = today.strftime("%d/%m/%Y")
    doc = Document()
    doc.styles['Normal'].font.name = "Arial MT"
    doc.styles['Normal'].font.size = Pt(10)
    para = doc.add_paragraph()
    text1 = para.add_run(carrier['companyname'])
    text1.font.name = 'Arial'
    text1.font.size = Pt(16)
    para = doc.add_paragraph()
    text2 = para.add_run('\n'+carrier['address']+'\nPh.: 708-710-5070\nEmail: Asexpress555@gmail.com')
    text2.font.size = Pt(12.5)
    para = doc.add_paragraph()
    run = para.add_run('\n\nPASSENGER RELEASE, INDEMNIFICATION AGREEMENT AND RIDER AUTHORIZATION')
    run.font.size = Pt(14)
    para = doc.add_paragraph()
    run = para.add_run('\nThe undersigned, being of lawful age, and with knowledge of the hazards involved in the transportation industry, hereby voluntarily agrees and/or represents as applicable:')
    run.font.size = Pt(11)
    run.font.name = 'Arial MT'
    para = doc.add_paragraph()
    run = para.add_run('That in exchange for free transportation on a company owned vehicle or driver leased vehicle, the undersigned ')
    run = para.add_run(str(passenger['fullname']))
    run.bold = True
    run = para.add_run(' hereby releases and forever discharges ')
    run = para.add_run(str(carrier['companyname']))
    run.bold = True
    run = para.add_run(' its affiliates and subsidiaries, officers and employees from any and all claims, losses, injuries or damages, included personal injury or death, resulting directly or indirectly from ')
    run = para.add_run(str(passenger['fullname']))
    run.bold = True
    run = para.add_run('\'s presence as a passenger on truck leased to ')
    run = para.add_run(str(carrier['companyname']))
    run.bold = True
    run = doc.add_paragraph()
    run = para.add_run('\n\nPassenger agrees to indemnify, defend and hold ')
    run = para.add_run(str(carrier['companyname']))
    run.bold = True
    run = para.add_run(' harmless from injury or loss resulting to ')
    run = para.add_run(str(carrier['companyname']))
    run.bold = True
    run = para.add_run(' any third party arising from the Passenger’s presence on any Company owned, or Driver leased vehicle.')
    para = doc.add_paragraph()
    run = para.add_run("Passenger Information: (please print legibly):\nName:")
    run = para.add_run('  ' + str(passenger['fullname']) + '  ')
    run.underline = True
    run = para.add_run("\nAddress:")
    run = para.add_run('  ' + str(passenger['address']) + '  ')
    run.underline = True
    run = para.add_run("\nDate of Birth:")
    run = para.add_run('  ' + str(passenger['dob']) + '  ')
    run.underline = True
    run = para.add_run("\nEmergency Contact Name and Phone Number:")
    run = para.add_run('  ' + str(passenger['emergencyname']) + '  ' + str(passenger['emergencyphone']))
    run.underline = True
    para = doc.add_paragraph()
    run = para.add_run('I, the undersigned, acknowledge that I have fully read this agreement understand its content and have voluntarily signed below.\n')
    table = doc.add_table(rows=1, cols=2)
    para = table.rows[0].cells[0].paragraphs[0]
    run = para.add_run('\n_____________________\n')
    run = para.add_run('Passenger Signature (if over the age of 18.)')
    run.font.size = Pt(9)
    run = para.add_run('\nDate:')
    run = para.add_run('  '+datetoday+'  ')
    run.underline = True
    para = table.rows[0].cells[1].paragraphs[0]
    run = para.add_run().add_picture(parentDir + '/public/driversdocs/temp/carrier_sign.png')
    run = para.add_run('\nI hereby authorize this passenger. \nAuthorized by:'+str(carrier['companyname'])+'\n')
    para = doc.add_paragraph('Ending date:')
    run = para.add_run('  until canceled  ')
    run.underline = True
    doc.save(parentDir + '/public/driversdocs/temp/passenger.docx')
    os.chmod(parentDir + '/public/driversdocs/temp/passenger.docx', 0o755)
    time.sleep(1)
    convert_docx_to_pdf(parentDir + "/public/driversdocs/temp/passenger.docx", parentDir + "/public/driversdocs/temp/passenger.pdf", parentDir+"/public/driversdocs/temp/")
    time.sleep(1)
    os.remove(parentDir + '/public/driversdocs/temp/passenger.docx')

def convert_docx_to_pdf(input_docx, output_pdf, parentDir):
    try:
        env_vars = {'HOME': '/var/www/html/tms/public/driversdocs/temp'}
        subprocess.run(['libreoffice', '--headless', '--convert-to', 'pdf', input_docx, '--outdir', parentDir], env=env_vars)
        os.rename(parentDir+'/passenger.pdf', output_pdf)
    except Exception as e:
        sys.exit()

def getCarrierInfo():
    cursor = connection.cursor()
    select_query = "SELECT iname, colvalue FROM settings WHERE type = 'fakecompany'"
    cursor.execute(select_query)
    res = cursor.fetchall()
    company = {
        'companyname': res[0][1],
        'address': res[1][1],
        'date': res[2][1],
        'mc': res[3][1],
        'usdot': res[4][1],
        }
    cursor.close()
    return company

def getPassenger():
    cursor = connection.cursor()
    select_query = "SELECT iname, colvalue FROM settings WHERE type = 'passenger'"
    cursor.execute(select_query)
    res = cursor.fetchall()
    passenger = {
        'fullname': res[0][1],
        'address': res[1][1],
        'dob': res[2][1],
        'emergencyname': res[3][1],
        'emergencyphone': res[4][1],
        }
    cursor.close()
    return passenger

parentDir = '/var/www/html/tms'
connection = mysql.connector.connect(**db_config)
if os.path.isfile(parentDir + '/public/driversdocs/temp/passenger.pdf'):
    os.remove(parentDir + '/public/driversdocs/temp/passenger.pdf')

try:
    carrier = getCarrierInfo()

    if carrier:
        passenger = getPassenger()
        if passenger:
            passengerDoc(parentDir,carrier,passenger)
        else:
            print('error', end='')
            connection.close()
            sys.exit()
    else:
        print('error', end='')
        connection.close()
        sys.exit()
finally:
    print('done', end='')
    connection.close()
