#!/usr/local/bin/python3.6
import sys
import logging
import pymysql
import boto3
import json


########################################################"
### Start of user inputs

parameter_name = '/devel' ### parameter with the db connection details. Lambda function should have permissions to access this parameter

### End of user inputs
########################################################"

ssm = boto3.client('ssm',region_name='us-west-2')
param_details=ssm.get_parameters(Names=[parameter_name],WithDecryption=True)
param = param_details.get('Parameters')[0]
config_values = json.loads(param.get('Value'))
rds = config_values['host']
user = config_values['userid']
password = config_values['password']
db = config_values['dbname']


logger = logging.getLogger()
logger.setLevel(logging.INFO)
#print(conn_str)

try:
	conn = pymysql.connect(rds,user=user,password=password,db=db)
except:
	logger.error('ERROR. Unexpected error: Could not connect to MySql instance.')
	sys.exit()

logger.info('SUCCESS. Connection to RDS mysql instance succeeded')

def lambda_handler(event, context):
	## This function will create a test table, insert some data and query the table

	item_count = 0
	with conn.cursor() as cursor:
		cursor.execute('DROP TABLE IF EXISTS table6')
		cursor.execute('CREATE TABLE table6 (id int, name varchar(255))')
		cursor.execute("insert into table6(id,name) values(123,'Jason')")
		cursor.execute("insert into table6(id,name) values(555,'Jenny')")
		cursor.execute("insert into table6(id,name) values(5555,'Bob')")
		conn.commit()
		cursor.execute('SELECT * FROM table6')
		for row in cursor:
			item_count += 1
			logger.info(row)
			print(row)

	return("Added %d items to RDS mysql table" %(item_count))



