import sys, os
import logging
import MySQLdb
import MySQLdb.cursors
import logging

class DataInjector(object):
	"""
	Helper class for parsing external data for data driven testing
	"""

	#logger = None 				#: logger to send loggin information to.  Logger comes from pytest test definitions
	db = {'db':None,
			'host':None,
			'user':None,
			'password':None,
			'database':None,
			'cursor':None,
			'results':None,
			'query':None}

	def __init__(self):
		pass
		#self.logger = logger

	def connect(self):
		try:
			
			self.db['db'] = MySQLdb.connect(host=self.db['host'], 
										user=self.db['user'],
										passwd=self.db['password'], 
										db=self.db['database'], 
										charset='utf8',
										cursorclass = MySQLdb.cursors.Cursor)
			self.db['cursor'] = self.db['db'].cursor()

		except MySQLdb.Error, e:
			print "Mysql Error %d: %s" % (e.args[0],e.args[1])
			
	def closeConnect(self):
		"""
		Closes the connetion
		"""
		try:
			self.db['db'].close()
		except MySQLdb.Error, e:
			print "Mysql Error %d: %s" % (e.args[0],e.args[1])

	def getTestData(self,table,limits=None):
		"""
		Retrieves all entries from db
		"""
		if limits is not None:
			sql = """SELECT * FROM """+str(table)+""" limit"""+str(limits)
		else:
			sql = """SELECT * FROM """+str(table)
		records = []

		try:
			self.cursor.execute(sql)
		except MySQLdb.Error, e:
			print "Mysql Error %d: %s" % (e.args[0],e.args[1])
		
		numrows = int(self.cursor.rowcount)

		if numrows >= 1:
			records = self.cursor.fetchall()
		else:
			print "No test data was returned. Maybe data for tests is empty?"

		#return records
		columnNames = self.getColumnNames(table)
		
		testData = []

		for record in records:
			rowNamesAndData = {}
			for i, column in enumerate(columnNames):
				rowNamesAndData[column] = record[i]
			testData.append(rowNamesAndData)
		
		return testData








dbInj = DataInjector()

dbInj.db = {'db':None,
			'host':'127.0.0.1',
			'user':'yid_user',
			'password':'y3ll0w1d',
			'database':'yid',
			'cursor':None,
			'results':None,
			'query':None}
dbInj.connect()
