from urllib2_aws4auth import aws_urlopen, Request
from urllib2 import  HTTPError
from urllib import urlencode
import json
import boto3
from pprint import pformat
	
REGION = 'us-east-2' 
SERVICE = 'execute-api'
ENDPOINT = 'https://l7o38q47a6.execute-api.us-east-2.amazonaws.com/default/ScadaProductMetrics' 
LOGGER = system.util.getLogger('activityLog')

def openSession():
	CREDS = boto3.Session().get_credentials()
	AWS_ACCESS_KEY_ID = CREDS.access_key
	AWS_SECRET_ACCESS_KEY = CREDS.secret_key
	TOKEN = CREDS.token
	
	OPENER = aws_urlopen(
		AWS_ACCESS_KEY_ID,
		AWS_SECRET_ACCESS_KEY,
		REGION,
		SERVICE,
		session_token=TOKEN,
		verify=False)
	return OPENER

def createActivityDetails(session, resource_type, resource, current_page, start_time, end_time = None):
	user = session.props.auth.user.userName
	session_id = session.props.id
	site = session.custom.fc
	start_time = system.date.format(start_time, 'yyyy-MM-dd HH:mm:ss')
	end_time = system.date.format(end_time, 'yyyy-MM-dd HH:mm:ss') if end_time != None else end_time
	user_UTCoffset = session.props.device.timezone.utcOffset 
	activityDetails = {'username':user, 
						'session_id':session_id, 
						'site': site, 
						'start_time': start_time, 
						'end_time':end_time, 
						'user_UTCoffset': user_UTCoffset, 
						'resource_type': resource_type, 
						'resource': resource,
						'current_page': current_page}
	return activityDetails

def logActivity(session, resource_type, resource, current_page, start_time, end_time = None):
	activityDetails = createActivityDetails(session, resource_type, resource, current_page, start_time, end_time)	
	user = session.props.auth.user.userName
	opener = openSession()
	params = activityDetails
	payload = json.dumps(params)
	method = 'POST'
	# in the headers the Ignition session username (session.props.auth.user.userName) must be supplied as 'X-Ignition-User'
	headers = {
		'Content-type': 'application/json',
		'X-Ignition-User': user
	}
	req = Request(url=ENDPOINT, method=method, data=payload, headers=headers)
	# open the request and process the read
	try:
		resp = opener(req)
		response = json.loads(resp.read())
		error = None
		print pformat(response)
	except HTTPError, e:
		error = str(e)
		response = None
		print error
		LOGGER.info(error)
	return {'error': error, 'response':response }
	
def callLogger(self, resource_type, resource = None, current_page= None):
	""" self is reference to the view. So if calling from shutdown script on the view, pass self.
		If calling from a component, pass self.view"""
	if self.session.custom.enable_activity_logging:
 		if self.session.props.device.type != 'designer':
 			end_time = system.date.now() if resource_type == 'page' else None
 			start_time = self.custom.activityLogger.start_time
			pageid = self.custom.activityLogger.pageid
 			resource = pageid if resource == None else resource
 			current_page = pageid if current_page == None else current_page
 			logActivity(self.session, resource_type, resource, current_page, start_time, end_time) 
	