# Print All Files in Folder C:\web\veldb\vimsreports

import os
import time 
import mysql.connector
from os import path  
from os import listdir  
from os.path import isfile, join
import shutil  
import win32api  
import win32print 
import subprocess

import default_setting

def file_print(cnx,frompath,printer):
# Kill any open Adobe Windows
	try:
		os.system("TASKKILL /F /IM AcroRD32.exe")
	except:
		pass

# 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)
# Archive Folder
		reportpath = frompath+"_arcv/"+printer
		if not os.path.isdir(reportpath):
			os.makedirs(reportpath)
# Move Report to Archive Folder
		if (frompath != reportpath):
			try:
				shutil.move(frompath+'/'+file, reportpath+'/'+file)
			except:
				pass
				
#		print(reportpath+'/'+file," ",printer)
# Use Default Program based on file extension		
		win32print.SetDefaultPrinter(printer)
		time.sleep(3)
		win_print(reportpath+'/'+file,printer)
# Kill any Adobe Windows
		time.sleep(3)
		try:
			os.system("TASKKILL /F /IM AcroRD32.exe")
		except:
			pass
# Clean-up variables
	try:
		del files  
		del reportpath
	except:
		pass

def win_print(filename, printer = None):
	if not printer:
		printer = win32print.GetDefaultPrinter()
		
	win32print.SetDefaultPrinter(printer)	
#	print("Printer:",printer)
	
	out = '/d:"%s"' % (printer)
	win32api.ShellExecute(0, "print", filename, out, ".", 0)

def print_map(cnx,reference):
	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
	

if __name__ == '__main__':
# 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,frompath,printer)
# Restore Default Printer Setting
	win32print.SetDefaultPrinter(default_printer)