import pymqi
import sys
import os
import time
import datetime

now = datetime.datetime.now()

# Import VIMS .py
import default_setting

def main(argvs):
# get Upload Directories from company settings
	defaults = default_setting.defaultSettings()
	uploadDirs = default_setting.companySettings(defaults)
	print(uploadDirs['interfacein'])
	
	return get_message(argvs,uploadDirs['interfacein'])
	
def get_message(argvs,directory):
	queue_manager = 'VIMSRRI10'	
	queue_name = 'VIMS.LSP_ASN.BMW'
	host = '172.18.21.5'
	port = '1415'
#	directory = 'c:/rrfiles/input'
	channel = 'SYSTEM.DEF.SVRCONN'
	
	prefix = 'IDOC'
	
# load values from input params
	if (len(argvs) > 1):
		queue_manager = argvs[1]
	if (len(argvs) > 2):
		queue_name = argvs[2]
	if (len(argvs) > 3):
		host = argvs[3]
	if (len(argvs) > 4):
		port = argvs[4]
	if (len(argvs) > 5):
		channel = argvs[5]
	if (len(argvs) > 6):
		directory = argvs[6]

	if (queue_name == 'VIMS.LSP_ASN.BMW'):
		prefix = 'ASN'
	if (queue_name == 'VIMS.LSP_SHP.BMW'):
		prefix = 'PCK'

#	return ('FAIL-TEST1',queue_manager,' ',queue_name,' ',host,' ',port,' ',directory,' ',channel)
		
	conn_info = '%s(%s)' % (host, port)

# Message Descriptor
	md = pymqi.MD()

# Get Message Options
	gmo = pymqi.GMO()
	gmo.Options = pymqi.CMQC.MQGMO_WAIT | pymqi.CMQC.MQGMO_FAIL_IF_QUIESCING
	gmo.WaitInterval = 5000 # 5 seconds

# Create and activate Queue_Manager
	qmgr = pymqi.connect(queue_manager, channel, conn_info)
	pcf = pymqi.PCFExecute(qmgr)

# Create Queue
	queue = pymqi.Queue(qmgr, queue_name, pymqi.CMQC.MQOO_INPUT_SHARED)

# Loop until message exists
	keep_running = True
	i = 0
	while keep_running:
		try:
# Wait up to to gmo.WaitInterval for a new message.
			message = queue.get(None, md, gmo)

# Process the message here..
			print('message:', message)
			message_string = str(message)
# Strip-Off control characters & delimiters
			message_string = message_string[2:-1]
# Create timestamp file name
			now = datetime.datetime.now()
			i = i+1
			file_name = prefix+now.strftime('%Y-%m-%d_%H-%M-%S-'+str(i))
			save_message(message_string,directory,file_name)
		
# Reset the MsgId, CorrelId & GroupId so that we can reuse
# the same 'md' object again.
			md.MsgId = pymqi.CMQC.MQMI_NONE
			md.CorrelId = pymqi.CMQC.MQCI_NONE
			md.GroupId = pymqi.CMQC.MQGI_NONE

		except pymqi.MQMIError as e:
			if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE:
# No messages, that's OK, we can ignore it.
				pass
			else:
# Some other error condition.
				return 'FAIL-'
				raise
	
	queue.close()
	qmgr.disconnect()

def save_message(message, directory, file_name):
# open output file
	file_path = directory+'/'+file_name+'.tmp'
	message_out = open(file_path,"w")
	message_out.write(message)		
	message_out.close()

# Initial Processing
if __name__ == '__main__':
	result = main(sys.argv)
if (result != "OK"):
	print("FAIL-",result)
else:
	print("OK")
