# from pymqi import *
import pymqi
import sys, os
from optparse import OptionParser
 
usage='Usage: %s [options] QMGRNAME QNAME'
def main(argv=None):
	if argv is None:
		argv = sys.argv
	try:
		(options,args)=parseOptions()
		if len(args)>2:
			raise MQException(2)
		if len(args)<2:
			raise MQException(4)
		qmgrName=args[0]
		qName=args[1]
       
#open queue manager
		qmgr = pymqi.connect('VIMSRRI10', 'SYSTEM.DEF.SVRCONN', '172.18.21.5(1415)')
#		qmgr = QueueManager(qmgrName)
#		gqdesc = pymqi.od( ObjectName=qName)
		Q = pymqi.Queue(qmgr, 'VIMS.LSP_ASN.BMW')
#		Q= Queue( qmgr, gqdesc)
		qDepth=Q.inquire(pymqi.CMQC.MQIA_CURRENT_Q_DEPTH)
		if options.depth==True:
#open queue for inquire
			print ('Current depth: %d' % qDepth)
			return 0
 
		if not options.index==None:
			if int(options.index)>=qDepth:
				raise MQException(5)
 
#open queue for browsing
		Q= pymqi.Queue( qmgr, 'VIMS.LSP_ASN.BMW', pymqi.CMQC.MQOO_BROWSE)
		msgDesc = pymqi.md()
		getOpts = pymqi.gmo(Options = pymqi.CMQC.MQGMO_BROWSE_NEXT)
		getOpts.WaitInterval = pymqi.CMQC.MQWI_UNLIMITED
 
		messages = []
		try:
			while 1:
				msg = Q.get(None, msgDesc, getOpts)
				messages.append(msg)
				if not options.all==True and options.index==None and not options.lifo==True:
					break 
# null MsgId and CorrelId, or cursor won't move up
# the Q
				msgDesc['MsgId'] = ''
				msgDesc['CorrelId'] = ''
		except pymqi.MQMIError as me:
#assume that error is raised when there are
#no more messages in queue
			pass
       
		if options.lifo==True:
			messages.reverse()
       
		if not options.all==True and options.index==None:
			messages=messages[0:1]
       
		if not options.index==None:
			printMessage(options,messages[int(options.index)])
		else:
			for message in messages:
				printMessage(options,message)
         
	except MQException as err:
		print  ('[ERROR]',err.errorCodes[err.msg])
		print  (usage % (sys.argv[0],))
		return err.code
	except pymqi.MQMIError as err:
		if err.reason==2033:
#no messages
			print ('No messages.') 
		else:
			print (err)
			return err.reason
  
def printMessage(options,message):
	if options.saveFile==True:
		seq=1
		if not options.fileName==None:
			fileName=options.fileName
		else:
			fileName='message'
			fileName='%s%05d' %(fileName,seq)
		while os.path.exists(fileName)==True:
			fileName=fileName[:-5]
			seq=seq+1
			fileName='%s%05d' %(fileName,seq)
		f=open(fileName,'w')
		f.write(message)
		f.close()
	else:
		if not options.noDelim==True:
			print ('-'*70)
	print (message)
 
def parseOptions():  
	parser = OptionParser(usage=(usage % ('%prog',)))
	parser.add_option("-f", 
		"--file", 
		action="store_true",
		dest="saveFile",
		help="Save message to a file with name 'message'.", )
	parser.add_option("-n", 
		"--file-name", 
		dest="fileName",
		help="File name for message. Use with -f option.", )
	parser.add_option("-i", 
		"--index", 
		dest="index",
		help="Browse message in the middle of queue.", )
	parser.add_option("-A", 
		"--all", 
		action="store_true",
		dest="all",
		help="Browse all messages. If messages are saved to file,"+
		" messages have sequence number in the file name.", )
	parser.add_option("-d", 
		"--depth", 
		action="store_true",
		dest="depth",
		help="Print just the queue depth.", )
	parser.add_option("-l", 
		"--lifo", 
		action="store_true",
		dest="lifo",
		help="Print last message first (Last-In-First-Out).", )
	parser.add_option("", 
		"--no-delim", 
		action="store_true",
		dest="noDelim",
		help="Do not print message delimeter.", )
   
	(options, args) = parser.parse_args()
	return (options, args)
 
#MQException class that holds application specific error codes
#and error messages
class MQException(Exception):
	errorCodes={'1': 'QMGRNAME, QNAME or MESSAGE missing.',
		'2': 'Too many arguments.',
		'3': 'File does not exist.',
		'4': 'QMGRNAME or QNAME missing.',
		'5': 'Index error. Not so many messages in queue.',
		}
	code=0
	def __init__(self, code):
		self.code=code
		self.msg = str(code)
     
if __name__ == "__main__":
	sys.exit(main())