import json
import csv
import numpy
import os
import configparser
import requests
import pandas as pd
import unittest
import cx_Oracle

class CommonOperations:
		def GetConfigFile():
				config = configparser.RawConfigParser()
				config.read('configurationfile.properties')
				return config

		def GetDBConnection():
			#Read Configuration Parameter file
			config = GetConfigFile()
			dbuser=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'dbuser')
			dbpass=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'dbpass')
			dbhost=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'dbhost')
			dbport=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'dbport')
			dbservice=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'dbservice')
			tns=cx_Oracle.makedsn(dbhost,dbport,dbservice)
			con=cx_Oracle.connect(dbuser,dbpass,tns)
			cur = con.cursor()
			return cur

		#Pass in a Query and get results
		def read_query(query):
			cursor = GetDBConnection()
			try:
				cursor.execute( query )
				# Get the fields name
				names = [x[0] for x in cursor.description]
				rows = cursor.fetchall()
				return pd.DataFrame( rows, columns=names)
			finally:
				if cursor is not None:
					cursor.close()

		def GenerateInMemberList():
				df = pd.read_csv('C:\Python\REST_API_Testing\RocketMilesRestAPI.csv')
				return df['MileagePlanNumber'].tolist()

		def GenerateInDF():
				df = pd.read_csv('C:\Python\REST_API_Testing\RocketMilesRestAPI.csv')
				return df

		def GenerateAPIURL():
				config = GetConfigFile()
				return "https://api." + os.environ['AIRGROUP_DEPLOY_TYPE'] + ".alaskaair.com" + config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'getmemberAPI')

		def GetMemberDataFromDB(in_mem_num):
				in_stmt = "{} IN ({})".format("MEM_NUM", ", ".join(["'" + str(n) + "'" for n in in_mem_num]))
				query="select mem_num,point_type_e_val,status_cd from siebel.s_loy_member where " + in_stmt
				return read_query(query)

		def PostAPIRequest():
				config = GetConfigFile()
				public_key=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'getmemberpublic_key')
				private_key=config.get(os.environ['AIRGROUP_DEPLOY_TYPE'], 'getmemberprivate_key')
				validate_api_url = GenerateAPIURL()
				in_mem_num = GenerateInMemberList()
				self.querydf = GetMemberDataFromDB(in_mem_num)
				location = 0
				respdfCols = ['MileagePlanNumber','StatusMessage','NoOfPoints']
				self.respdf = pd.DataFrame(columns=respdfCols)
				df = GenerateInDF()
				for MPNum in GenerateInMemberList():  
					print('Posting Request')
					data = {
                        "body":
                            {
                                "MileagePlanNumber":MPNum,
			                    "PartnerName": df[df['MileagePlanNumber'] == MPNum]['PartnerName'].values[0],
			                    "LastName": df[df['MileagePlanNumber'] == MPNum]['LastName'].values[0],
			                    "FirstName": df[df['MileagePlanNumber'] == MPNum]['FirstName'].values[0]
			                }
			            }
					r = requests.post(validate_api_url, json = data, auth=(public_key, private_key))
					self.respdf.loc[location] = [r.json()['MileagePlanNumber'],r.json()['StatusMessage'], r.json()['NoOfPoints']]
					location = location + 1
					if r.status_code == requests.codes.ok:
						print('response status code is: ' + str(r.status_code))
					else:
						print('received' + r.status_code + 'from server')

class GetMemInifoAPITestCls(unittest.TestCase, CommonOperations):
	def setUp(self):
		#self.verificationErrors = []
		#Open DB Connection
		PostAPIRequest()

	def test_Statusmessage(self):
		for key,value in self.respdf.iterrows():
				try: 
						print('TestCase1: Executing StatusMessage validation')
						self.assertEqual(value[1], 'Member is valid')
				except: 
						print('Member is not valid')
				try:
						print('TestCase2: Executing Points validation')
						self.assertEqual(int(value[2]), self.querydf[self.querydf['MEM_NUM'] == value[0]]['POINT_TYPE_E_VAL'].values[0])
				except: 
						print('NoOfPoints retrieved is not valid')

if __name__ == '__main__':
	unittest.main()