"""
Copyright 2018 Attunity
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# coding: utf-8
import os, sys, time, datetime, json, subprocess
from collections import OrderedDict
from datetime import timezone

# import AEM-Client
from aem_client import *

if sys.version_info > (3,):
	print('Using environment Python 3.X\n')
else:
	print('Using environment Python 2.X\n')

# Utility class for Examples
class Utils(object):
	@staticmethod
	def dollar_type(obj):
		"""
		get attribute '$type'
		"""
		return getattr(obj, '$type')
	# Utils.dollar_type

	@staticmethod
	def enum_name(enum_val):
		return enum_val.name
	# Utils.enum_name

	@staticmethod
	def print_action_title(action_text):
		print('\n############################################################')
		print('\n{0}\n'.format(str(action_text) ) )
	# Utils.print_action_title
	
	@staticmethod
	def print_action_title_without_separator(action_text):
		print('\n{0}\n'.format(str(action_text) ) )
	# Utils.print_action_title_without_separator
	
	@staticmethod
	def time_sleep(duration=3, show_msg=True):
		"""
		sleep for duration (in seconds)
		"""
		if show_msg:
			print('Sleeping for: {0} seconds'.format(duration))
		time.sleep(duration)
	# Utils.time_sleep

	@staticmethod
	def get_b64_user_pass(username, password):
		"""
		return a base64 of 'username:password'
		"""
		username_password_str = str.encode('{0}:{1}'.format(username, password))
		return base64.b64encode(username_password_str).decode('ascii')
	# Utils.get_b64_user_pass

	@staticmethod
	def changed_initial(current_value, predefine_value, param_name):	
		if current_value == predefine_value:
			raise RuntimeError('Please replace param: "{0}", value:"{1}", to the real value.'.format(param_name, predefine_value ) )
	# Utils.changed_initial

	@staticmethod
	def print_dict_attr(obj, attr_name):
		for key in obj.__dict__:
			item = obj.__dict__[key]					
			if hasattr(item, attr_name):
				inner_list = getattr(item,attr_name)
				for inner_item in inner_list:
					print('\t{0}:\t{1}'.format(inner_item.name, key))
	# Utils.print_dict_attr
# END of class Util

class PythonProgram(object):
	def __init__(self, ):
		"""		
		### you can use the environment for username and password
		#Get user_name and password from environment			
		username = os.getenv("AEM_USERNAME", default=None)
		print('AEM_USERNAME = ' + env_username)
		password = os.getenv("AEM_PASSWORD", default=None)
		print('AEM_PASSWORD = ' + env_password)
		"""

		### Information for connecting to AEM (replace placeholders with actual connection details)
		domain = 'LM'
		username = 'sapipqlikadmin'
		password = base64.b64decode(b'OVdnJDQ4JGJCYmUkbjI===').decode('utf-8')
		aem_machine_name = 'vmpip-q525jzty.lm.lmig.com'

		Utils.changed_initial(domain, 'DOMAIN', 'domain')
		Utils.changed_initial(username, 'USER', 'username')
		Utils.changed_initial(password, 'PASSWORD', 'password')
		Utils.changed_initial(aem_machine_name, 'some-host', 'aem_machine_name')
		# Combine domain and user name - domain\\username
		domain_username = '{0}\\{1}'.format(domain, username)	

		print('Connecting to AemClient with user "{0}" on machine name: "{1}"...'.format(domain_username, aem_machine_name))
		try:
			# The format of credentials AemClient must get is domain\\username:password base64 encoded
			b64_username_password = Utils.get_b64_user_pass(domain_username, password)
			# Create an instance of AemClient
			self.aem_client = AemClient(b64_username_password, aem_machine_name, verify_certificate=False)
			print('Done.')			
			print('\n############################################################')
		except Exception as ex:
			print('Failed connecting to AemClient')
			print(ex)	
			self.aem_client = None
	# end function __init__ for ExamplePythonProgram
	
	def get_audit_details(self, starttime, endtime):
		try:
			resp = self.aem_client.export_audit_trail(starttime, endtime)
			return resp
		except Exception as ex:
			print('Error aem_export_audit_details')
			print(ex)
			return None
	# end function get_task_details

# END class PythonProgram


#################################
#		example_main			#
#################################
def main():

	# setup_aem_client
	program = PythonProgram()
	if program.aem_client == None:
		print('Error: in aem_client,\nExiting.')
		exit()

	past24hours = 864000000000
	p = subprocess.Popen(["powershell", "./getCurrentTicks.ps1"], stdout=subprocess.PIPE)
	result = p.communicate()
	endticks = "%s" % result[0].decode("utf-8").rstrip().replace("'","")
	endticks = int(endticks)
	startticks = endticks - past24hours

	Utils.print_action_title_without_separator('Retrieving audit details......')
	
	audit_data = program.get_audit_details(str(startticks), str(endticks))
	audit_info = open('audit_data.log', 'bw')
	audit_info.write(audit_data)
	audit_info.close()
	audit_info = open('audit_data.log', 'br')
	for line in audit_info:
		print(line.decode('utf-8'))
	audit_info.close()
	print('\nDONE.')

### END of function MAIN_USE
##############################################################


if __name__ == '__main__':
	main()
