#!C:/Users/administrator.AUTDOM01/AppData/Local/Programs/Python/Python36-32/python.exe

# Print All Files in Folder C:\web\veldb\vimsreports
import sys
import os
import time 
import subprocess
import mysql.connector
from os import path  
from os import listdir  
from os.path import isfile, join
import shutil  
import win32api  
import win32print 

import default_setting

def file_print(cnx,frompath):
    printok = 0
# list all the files in Report folder  
    files = [ f for f in listdir(frompath) if isfile(join(frompath,f)) ]  
    e = 0 
# Loop Through Files	
    for file in files:
# get print mapping based on file name
        reference = file[0:5]
#        printer = print_map(cnx,reference)
        printer = "172.18.21.144"
        try:
            printok = win_print(frompath+'/'+file,printer)
            time.sleep(5)		
            try:
                os.remove(frompath+'/'+file)
            except:
                pass
        except Exception as Err:
            print("Error Printing ",frompath+'/'+file," ",printer,Err)
            pass
            
        print ("Print Status = "+str(printok))

# Clean-up variables
    time.sleep(5)
    try:
        del files  
#        del reportpath
    except:
        pass

def win_print(filename, printer = None):
    printok = 0	    
# run print
    pgmPath = '"c:/Progra~1/LibreOffice/program/soffice.exe" -pt'
    printPath = '"172.18.21.144"';
    filePath = '"'+filename+'"';
    result = subprocess.run([pgmPath, '-f', printPath,filePath])
    print("RESULT",result)
		
# wait before killing the default program - give the print program time to complete		
    time.sleep(15)
	
    return printok

def print_map(cnx,reference):
    printerName = "printer"
#	printerName = win32print.GetDefaultPrinter()
# connection
    cursor = cnx.cursor(dictionary=True)
# Get printer mpped to this reference	
    dataQuery = "SELECT printer_address AS printer_address FROM printer_mapping WHERE printer_code='"+reference+"' LIMIT 1"
    cursor.execute(dataQuery) 
    row = cursor.fetchone()
    if row:
        printerName = row['printer_address']
    cursor.close()
    return printerName

def main(printfile):
# Default Connection / System Settings
	defaults = default_setting.defaultSettings()
# mySql Connector
	cnx = mysql.connector.connect(user=defaults['dbuser'], password=defaults['dbpwd'],host=defaults['dbhost'],database=defaults['dbase'])
# List Available Printer Names	
#	for printers in win32print.EnumPrinters(2):
#		print("Printer: ",printers[2])
# Set path to report files folder	
#	frompath = r"c:\web\veldb\vimsreports" 
#	default_printer= win32print.GetDefaultPrinter()
#	printer= win32print.GetDefaultPrinter()
# Print & Archive Reports
	file_print(cnx,printfile)
# Restore Default Printer Setting
#	win32print.SetDefaultPrinter(default_printer)
	
if __name__ == '__main__':
#	while True:
#		sys.stdout.write("\r")
#		main()
#		for remaining in range(60, 0, -1):
#			sys.stdout.write("\r")
#			sys.stdout.write("{:2d} seconds remaining.".format(remaining))
#			sys.stdout.flush()
#			time.sleep(1)

# Split file name & printer from input parm
    parm1 = ""
    
#	arg = sys.argv[1]
#	parm1 = arg

# Set path to report files folder
    if (parm1 == "" or parm1 == None):
        parm1 = "c:/remoteprint"	
		
# Store Default Printer name		
#	default_printer= win32print.GetDefaultPrinter()
		
    main(parm1)
	
# Restore Default Printer Setting
#	win32print.SetDefaultPrinter(default_printer)
	
    print ("Python-"+str(parm1))