from appservices.common.util import *

admin_logs = Blueprint("admin_logs",__name__)


@admin_logs.route("/sms_logs_list",methods=["POST","GET"])
def sms_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	smsLogsList = []
	pagination = None
	adminId = session.get("adminId")
	permissionsList = check_permissions(session.get("adminId"),"smslogsPermissions")
	print(permissionsList,"((((((((permissionsList))))))))")
	if "view" in permissionsList:
		try:
			otp_checks_queryset = OtpChecks.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = otp_checks_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_otpchecks = otp_checks_queryset[start:end]
			
			snoCount = start
			for each_otp_check in total_otpchecks:
				snoCount +=1
				smsLogDict = {
				"id":str(each_otp_check.id),
				"otpCode":each_otp_check.otpCode,
				"phoneNumber":each_otp_check.phoneNumber,
				"attempts":each_otp_check.attempts,
				"otpReason":each_otp_check.otpReason,
				"createdOn":each_otp_check.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				if each_otp_check.userId:
					smsLogDict["name"]=each_otp_check.userId.fullName
				else:
					smsLogDict["name"]=each_otp_check.adminId.userName
				smsLogDict["snoCount"]=snoCount
				smsLogsList.append(smsLogDict)
			return render_template("super_admin_templates/sms_logs_list.html",
				pagination=pagination,
				smsLogsList=smsLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched sms logs data!!"
			return render_template("super_admin_templates/sms_logs_list.html", 
				error=error,
				pagination=pagination,
				smsLogsList=smsLogsList
				)
	else:
		flash("Staff member does not have given view sms logs permissions!!")
		return redirect(url_for("admin.dashboard"))

@admin_logs.route("/merchant_logs_list",methods=["POST","GET"])
def merchant_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	merchantLogsList = []
	pagination = None
	permissionsList = check_permissions(session.get("adminId"),"merchantLogsPermissions")
	if "view" in permissionsList:
		try:
			merchant_logs_queryset = LoginReportLogs.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = merchant_logs_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_merchants_logs = merchant_logs_queryset[start:end]
			
			snoCount = start
			for each_merchant_log in total_merchants_logs:
				snoCount +=1
				merchantLogDict = {
				"id":str(each_merchant_log.id),
				"merchantName":each_merchant_log.userId.fullName,
				"phoneNumber":each_merchant_log.phoneNumber,
				"otpCode":each_merchant_log.otpCode,
				"attempts":each_merchant_log.attempts,
				"ipAddress":each_merchant_log.ipAddress,
				"latitude":each_merchant_log.latitude,
				"longitude":each_merchant_log.longitude,
				"os":each_merchant_log.os,
				"userAgent":each_merchant_log.userAgent,
				"loginBrowser":each_merchant_log.loginBrowser,
				"deviceName":each_merchant_log.deviceName,
				"createdOn":each_merchant_log.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				merchantLogDict["snoCount"]=snoCount
				merchantLogsList.append(merchantLogDict)
			return render_template("super_admin_templates/merchant_logs_list.html",
				pagination=pagination,
				merchantLogsList=merchantLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched merchant logs data!!"
			return render_template("super_admin_templates/merchant_logs_list.html", 
				error=error,
				pagination=pagination,
				merchantLogsList=merchantLogsList
				)
	else:
		flash("Staff member does not have given view merchant logs permissions!!")
		return redirect(url_for("admin.dashboard"))


@admin_logs.route("/admin_otp_logs_list",methods=["POST","GET"])
def admin_otp_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	adminLogsList = []
	pagination = None
	permissionsList = check_permissions(session.get("adminId"),"adminOtpLogsPermissions")
	if "view" in permissionsList:
		try:
			admin_logs_queryset = SuperAdminLogs.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = admin_logs_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_admin_logs = admin_logs_queryset[start:end]
			
			snoCount = start
			for each_admin_log in total_admin_logs:
				snoCount +=1
				adminLogDict = {
				"id":str(each_admin_log.id),
				"adminName":each_admin_log.adminId.userName,
				"otpCode":each_admin_log.otpCode,
				"attempts":each_admin_log.attempts,
				"ipAddress":each_admin_log.ipAddress,
				"userAgent":each_admin_log.userAgent,
				"loginBrowser":each_admin_log.loginBrowser,
				"createdOn":each_admin_log.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				adminLogDict["snoCount"]=snoCount
				adminLogsList.append(adminLogDict)

			# Pagination object for rendering pagination controls in the template
			pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right", record_name="admin_logs")
			return render_template("super_admin_templates/admin_otp_logs_list.html",
				pagination=pagination,
				adminLogsList=adminLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched admin logs data!!"
			return render_template("super_admin_templates/admin_otp_logs_list.html", 
				error=error,
				pagination=pagination,
				adminLogsList=adminLogsList
				)
	else:
		flash("Staff member does not have given view admin otp logs permissions!!")
		return redirect(url_for("admin.dashboard"))


@admin_logs.route("/api_logs_list",methods=["POST","GET"])
def api_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	apiLogsList = []
	pagination = None
	permissionsList = check_permissions(session.get("adminId"),"apiLogsPermissions")
	if "view" in permissionsList:
		try:
			if not session.get("adminId"):
				return redirect("admin_login")
			adminId = session.get("adminId")

			api_logs_queryset = ApiLogs.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = api_logs_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_api_logs = api_logs_queryset[start:end]
			
			snoCount = start
			for each_api_logs in total_api_logs:
				snoCount +=1
				apiLogDict = {
				"id":str(each_api_logs.id),
				"walletType":each_api_logs.walletType,
				"transactionAPIId":each_api_logs.transactionAPIId,
				"apiCallingType":each_api_logs.apiCallingType,
				"apiCallingUrl":each_api_logs.apiCallingUrl,
				"requestData":each_api_logs.requestData,
				"responseData":each_api_logs.responseData,
				"clientIp":each_api_logs.clientIp,
				"platformType":each_api_logs.platformType,
				"createdOn":each_api_logs.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				requestList = []
				for each_dict in each_api_logs.requestData:
					dict_items_data = each_dict.items()
					for each_key,each_value in dict_items_data:
						requestDict = {
						"keyName":each_key,
						"valueName":each_value
						}
						requestList.append(requestDict)
				apiLogDict["requestList"]=requestList

				responseList = []

				for each_dict in each_api_logs.responseData:
					for each_key in each_dict.keys():
						responseDict ={
						"keyName":each_key,
						"valueName":each_dict[each_key]
						}
						responseList.append(responseDict)
				apiLogDict["responseList"]=responseList

				if each_api_logs.requestDate:
					apiLogDict["requestDate"] = each_api_logs.requestDate.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				else:
					apiLogDict["requestDate"] = ""

				if each_api_logs.responseDate:
					apiLogDict["responseDate"] = each_api_logs.responseDate.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				else:
					apiLogDict["responseDate"] = ""

				apiLogDict["snoCount"]=snoCount
				apiLogsList.append(apiLogDict)

			# Pagination object for rendering pagination controls in the template
			pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right", record_name="api_logs")
			return render_template("super_admin_templates/api_logs_list.html",
				pagination=pagination,
				apiLogsList=apiLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched api logs data!!"
			return render_template("super_admin_templates/api_logs_list.html", 
				error=error,
				pagination=pagination,
				apiLogsList=apiLogsList
				)  
	else:
		flash("Staff member does not have given view api logs permissions!!")
		return redirect(url_for("admin.dashboard"))      


@admin_logs.route("/client_logs_list",methods=["POST","GET"])
def client_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	clientLogsList = []
	pagination = None
	permissionsList = check_permissions(session.get("adminId"),"clientPermissions")
	if "view" in permissionsList:
		try:
			if not session.get("adminId"):
				return redirect("admin_login")
			adminId = session.get("adminId")

			client_logs_queryset = ClientLogs.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = client_logs_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_client_logs = client_logs_queryset[start:end]
			
			snoCount = start
			for each_client_logs in total_client_logs:
				snoCount +=1
				clientLogDict = {
				"id":str(each_client_logs.id),
				"walletType":each_client_logs.walletType,
				"apiCallingType":each_client_logs.apiCallingType,
				"apiCallingUrl":each_client_logs.apiCallingUrl,
				"transactionAPIId":str(each_client_logs.transactionAPIId.id),
				"requestData":each_client_logs.requestData,
				"responseData":each_client_logs.responseData,
				"clientIp":each_client_logs.clientIp,
				"platformType":each_client_logs.platformType,
				"createdOn":each_client_logs.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				requestList = []
				for each_dict in each_client_logs.requestData:
					dict_items_data = each_dict.items()
					for each_key,each_value in dict_items_data:
						requestDict = {
						"keyName":each_key,
						"valueName":each_value
						}
						requestList.append(requestDict)
				clientLogDict["requestList"]=requestList

				responseList = []
				for each_dict in each_client_logs.responseData:
					dict_items_data = each_dict.items()
					for each_key,each_value in dict_items_data:
						responseDict = {
						"keyName":each_key,
						"valueName":each_value
						}
						responseList.append(responseDict)
				clientLogDict["responseList"]=responseList

				if each_client_logs.transactionAPIId:
					clientLogDict["transactionAPIId"] = str(each_client_logs.transactionAPIId.id)
				else:
					clientLogDict["transactionAPIId"] = ""

				if each_client_logs.requestDate:
					clientLogDict["requestDate"] = each_client_logs.requestDate.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				else:
					clientLogDict["requestDate"] = ""

				if each_client_logs.responseDate:
					clientLogDict["responseDate"] = each_client_logs.responseDate.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				else:
					clientLogDict["responseDate"] = ""

				clientLogDict["snoCount"]=snoCount
				clientLogsList.append(clientLogDict)

			# Pagination object for rendering pagination controls in the template
			pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right", record_name="client_logs")
			return render_template("super_admin_templates/client_logs_list.html",
				pagination=pagination,
				clientLogsList=clientLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched client logs data!!"
			return render_template("super_admin_templates/client_logs_list.html", 
				error=error,
				pagination=pagination,
				clientLogsList=clientLogsList
				)  
	else:
		flash("Staff member does not have given view client logs permissions!!")
		return redirect(url_for("admin.dashboard"))

@admin_logs.route("/admin_logs_list",methods=["POST","GET"])
def admin_logs_list():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	adminsLogsList = []
	pagination = None
	permissionsList = check_permissions(session.get("adminId"),"adminLogsPermissions")
	if "view" in permissionsList:
		try:
			if not session.get("adminId"):
				return redirect("admin_login")
			adminId = session.get("adminId")

			admin_logs_queryset = AdminLogs.objects(status__in=[0,1]).order_by("-id").all()

			# Get the current page from the query parameters
			page = request.args.get(get_page_parameter(), type=int, default=1)

			per_page = 20  # Number of items per page

			# Query the database for the current page's data
			total_count = admin_logs_queryset.count()

			start = (page - 1) * per_page

			end = min(start + per_page, total_count)

			total_admin_logs = admin_logs_queryset[start:end]
			
			snoCount = start
			for each_admin_log in total_admin_logs:
				snoCount +=1
				adminLogDict = {
				"id":str(each_admin_log.id),
				"adminName":each_admin_log.adminId.userName,
				"message":each_admin_log.message,
				"createdOn":each_admin_log.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p")
				}
				adminLogDict["snoCount"]=snoCount
				adminsLogsList.append(adminLogDict)

			# Pagination object for rendering pagination controls in the template
			pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right", record_name="admin_logs")
			return render_template("super_admin_templates/admin_logs_list.html",
				pagination=pagination,
				adminsLogsList=adminsLogsList
				)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetched admin logs data!!"
			return render_template("super_admin_templates/admin_logs_list.html", 
				error=error,
				pagination=pagination,
				adminsLogsList=adminsLogsList
				)
	else:
		flash("Staff member does not have given view admin logs permissions!!")
		return redirect(url_for("admin.dashboard"))