from appservices.common.util import *
from appservices.common.form_schemas import *
third_party_integrations = Blueprint("third_party_integrations",__name__)

@third_party_integrations.route("/add_site", methods=["POST", "GET"])
@adminid_access_token_required
@csrf_protect
def add_site():
	data_status={"responseStatus":0,"result":""}
	try:
		if not session.get("adminId"):
			flash("Session expired","danger")
			data_status["responseStatus"]=4
			return data_status
		adminId = session.get("adminId")
		
		csrf_token = request.form.get("csrf_token")
		print(csrf_token,"((((((((((((((csrf_token))))))))))))))")
		latitude = request.form.get("latitude", "")
		longitude = request.form.get("longitude", "")
		loginBrowser = request.headers.get("Sec-Ch-Ua")
		if loginBrowser:
			loginBrowseData = loginBrowser.split(";")
			browser = loginBrowseData[0]
		else:
			loginBrowseData = request.headers.get('User-Agent').split(";")
			browser = loginBrowseData[0]

		client_ip=0
		# Extracting client IP address
		if request.headers.getlist("X-Forwarded-For"): 
			client_ip = request.headers.getlist("X-Forwarded-For")[0]
		else:
			client_ip = request.remote_addr

		actionDate=datetime.datetime.now()
		
		permissionsList = check_permissions(adminId,"thirdPartyIntegrationPermissions")
		if "add" in permissionsList:

			if request.method == "POST":
				form=ThirdPartyIntigrationForm()
				# Retrieve form data
				name = request.form.get("name", "")
				ipAddress = request.form.get("ipAddress", "")
				trnIdentifier = request.form.get("trnIdentifier", "")
				enablePayin = request.form.get("enablePayin",False)
				payinPaymentGatewayId = request.form.getlist("payinPaymentGatewayId")
				payinWebhook = request.form.get("payinWebhook", "")
				enablePayout = request.form.get("enablePayout",False)
				payoutPaymentGatewayId = request.form.getlist("payoutPaymentGatewayId")
				payoutVAWebhook = request.form.get("payoutVAWebhook", "")
				payoutValidationWebhook = request.form.get("payoutValidationWebhook", "")
				payoutAlertsWebhook = request.form.get("payoutAlertsWebhook", "")
				payoutWebhook = request.form.get("payoutWebhook", "")
				# payinPaymentGatewaysList = request.form.getlist("payinPaymentGatewaysList")
				# payoutPaymentGatewaysList = request.form.getlist("payoutPaymentGatewaysList")

				jsonData = request.form.to_dict(flat=True)
				requestData = [jsonData]
				updatedrequestData = [jsonData]
				
				apiKey = random_alphanumeric_generate(12)
				secretKey = str(secrets.token_hex(12))
				if form.validate_on_submit():

				# if name and not is_valid_alphanumeric(name):
				#     flash("Name contain only alphanumeric characters, spaces, and specific special characters:@#$()+_-/")
				#     return redirect(url_for("third_party_integrations.get_sites_list"))

				# if ipAddress and not is_valid_numeric_allow_muldots(ipAddress):
				#     flash("ipAddress contain only numeric characters and allows multiple dots.")
				#     return redirect(url_for("third_party_integrations.get_sites_list"))

				# if trnIdentifier and not is_valid_alphanumeric(trnIdentifier):
				#     flash("Transaction Identifier contain only alphanumeric characters, spaces, and specific special characters:@#$()+_-/")
				#     return redirect(url_for("third_party_integrations.get_sites_list"))

					if not enablePayin:
						payinPaymentGatewayId = None
						payinWebhook = ""

					if not enablePayout:
						payoutPaymentGatewayId = None
						payoutWebhook = ""
						payoutAlertsWebhook = ""
						payoutValidationWebhook = ""
						payoutVAWebhook = ""

					if payinPaymentGatewayId:
						payinPaymentGatewaysList=[ObjectId(each_payin_pg) for each_payin_pg in payinPaymentGatewayId]
					else:
						payinPaymentGatewaysList = []

					if payoutPaymentGatewayId:
						payoutPaymentGatewaysList=[ObjectId(each_payout_pg) for each_payout_pg in payoutPaymentGatewayId]
					else:
						payoutPaymentGatewaysList = []

					if name and ipAddress and apiKey and secretKey:
						try:
							admin_queryset = SuperAdmin.objects(id=adminId,status=1).first()
							if admin_queryset:
								message=admin_queryset.userName+" "+name+" Site saved successfully!"
								save_admin_log_table = save_admin_logs_data(adminId,None,None,"add_site","create",actionDate,client_ip,browser,message,requestData,updatedrequestData,latitude,longitude) 
							third_party_integration = ThirdPartyMerchants(
								name=name,
								ipAddress=ipAddress,
								apiKey=apiKey,
								secretKey=secretKey,
								enablePayin=enablePayin,
								trnIdentifier=trnIdentifier,
								# payinPaymentGatewayId=ObjectId(payinPaymentGatewayId) if payinPaymentGatewayId else None,
								payinWebhook=payinWebhook,
								enablePayout=enablePayout,
								# payoutPaymentGatewayId=ObjectId(payoutPaymentGatewayId) if payoutPaymentGatewayId else None,
								payoutWebhook=payoutWebhook,
								payoutAlertsWebhook=payoutAlertsWebhook,
								payoutValidationWebhook=payoutValidationWebhook,
								payoutVAWebhook=payoutVAWebhook,
								payinPaymentGatewaysList=payinPaymentGatewaysList,
								payoutPaymentGatewaysList=payoutPaymentGatewaysList,
								createdOn=datetime.datetime.now(),
								status=1
								)
							save_table = third_party_integration.save()

							flash("Site saved successfully","success")
							data_status["responseStatus"]=1
							return data_status
						except Exception as e:
							flash("Unable to save site details","danger")
							app.logger.error(traceback.format_exc())
							data_status["responseStatus"]=4
							return data_status
					else:
						flash("Required fields are missing!","danger")
						data_status["responseStatus"]=2
						return data_status
				else:
					data_status['result']=form.errors
					print("(((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))",form.errors)
					return data_status
			else:
				flash("The request you made is invalid. Please check and try again.", "danger")
				data_status["responseStatus"]=4
				return data_status
		else:
			flash("The staff member does not have permission to create a site.", "danger")

			data_status["responseStatus"]=4
			return data_status
	except Exception as e:
		app.logger.error(traceback.format_exc())
		error = "Unable to save site details!"
		flash("Unable to save pattern details.", "danger")
		data_status["responseStatus"]=4
		return data_status



@third_party_integrations.route("/update_site", methods=["POST"])
@adminid_access_token_required
@csrf_protect
def update_site():
	data_status={"responseStatus":0,"result":""}
	if not session.get("adminId"):
		flash("Session Expired","danger")
		data_status["responseStatus"]=4
		return data_status
	adminId = session.get("adminId")
	
	csrf_token = request.form.get("csrf_token")
	print(csrf_token,"((((((((((((((csrf_token))))))))))))))")
	latitude = request.form.get("latitude", "")
	longitude = request.form.get("longitude", "")	
	loginBrowser = request.headers.get("Sec-Ch-Ua")
	if loginBrowser:
		loginBrowseData = loginBrowser.split(";")
		browser = loginBrowseData[0]
	else:
		loginBrowseData = request.headers.get('User-Agent').split(";")
		browser = loginBrowseData[0]

	existing_record = ""
	client_ip=0
	# Extracting client IP address
	if request.headers.getlist("X-Forwarded-For"): 
		client_ip = request.headers.getlist("X-Forwarded-For")[0]
	else:
		client_ip = request.remote_addr

	actionDate=datetime.datetime.now()
	siteId = request.args.get("siteId","")  # Get the site ID for updates
	try:
		permissionsList = check_permissions(session.get("adminId"),"thirdPartyIntegrationPermissions")
		if "edit" in permissionsList:
			form=ThirdPartyIntigrationForm(request.form,current_id=siteId)
			# Retrieve form data
		
			name = request.form.get("name", "")
			ipAddress = request.form.get("ipAddress", "")
			enablePayin = request.form.get("enablePayin",False)
			payinPaymentGatewayId = request.form.getlist("payinPaymentGatewayId")
			trnIdentifier = request.form.get("trnIdentifier", "")
			payinWebhook = request.form.get("payinWebhook", "")
			enablePayout = request.form.get("enablePayout",False)
			payoutPaymentGatewayId = request.form.getlist("payoutPaymentGatewayId")
			payoutWebhook = request.form.get("payoutWebhook", "")
			payoutVAWebhook = request.form.get("payoutVAWebhook", "")
			payoutValidationWebhook = request.form.get("payoutValidationWebhook", "")
			payoutAlertsWebhook = request.form.get("payoutAlertsWebhook", "")
			# payinPaymentGatewaysList = request.form.getlist("payinPaymentGatewaysList")
			# payoutPaymentGatewaysList = request.form.getlist("payoutPaymentGatewaysList")
			
			jsonData = request.form.to_dict(flat=True)
			
			if form.validate_on_submit():
			# if name and not is_valid_alphanumeric(name):
			#     flash("Name contain only alphanumeric characters, spaces, and specific special characters:@#$()+_-/")
			#     return redirect(url_for("third_party_integrations.get_sites_list"))

			# if ipAddress and not is_valid_numeric_allow_muldots(ipAddress):
			#     flash("ipAddress contain only numeric characters and allows multiple dots.")
			#     return redirect(url_for("third_party_integrations.get_sites_list"))

			# if trnIdentifier and not is_valid_alphanumeric(trnIdentifier):
			#     flash("Transaction Identifier contain only alphanumeric characters, spaces, and specific special characters:@#$()+_-/")
			#     return redirect(url_for("third_party_integrations.get_sites_list"))

				# print(payoutPaymentGatewaysList,"((((((((payoutPaymentGatewaysList))))))))")
				if not enablePayin:
					enablePayin=False
					payinPaymentGatewayId = None
					payinWebhook = ""
				else:
					enablePayin=True
					# payinPaymentGatewayId=ObjectId(payinPaymentGatewayId)

				if not enablePayout:
					enablePayout=False
					payoutPaymentGatewayId = None
					payoutWebhook = ""
					payoutVAWebhook = ""
					payoutValidationWebhook = ""
					payoutAlertsWebhook = ""
				else:
					enablePayout=True
					# payoutPaymentGatewayId=ObjectId(payoutPaymentGatewayId)

				if siteId and name and ipAddress:
					try:
						third_party_integration = ThirdPartyMerchants.objects(id=siteId).first()
						admin_queryset = SuperAdmin.objects(id=adminId,status=1).first()
						existing_record = third_party_integration.to_json()
						message=admin_queryset.userName+" "+name+" Site updated successfully!"
						requestData=[third_party_integration]
						updatedrequestData=[jsonData]
						save_admin_log_table = save_admin_logs_data(adminId,None,None,"update_site","update",actionDate,client_ip,browser,message,requestData,updatedrequestData,latitude,longitude) 


						if third_party_integration:
							third_party_integration.update(
								name=name,
								ipAddress=ipAddress,
								enablePayin=enablePayin,
								trnIdentifier=trnIdentifier,
								payinPaymentGatewayId=None,
								payinWebhook=payinWebhook,
								enablePayout=enablePayout,
								payoutPaymentGatewayId=None,
								payoutWebhook=payoutWebhook,
								payoutAlertsWebhook=payoutAlertsWebhook,
								payoutValidationWebhook=payoutValidationWebhook,
								payoutVAWebhook=payoutVAWebhook
							)
							if payinPaymentGatewayId:
								third_party_integration.update(payinPaymentGatewaysList=[ObjectId(each_payin_pg) for each_payin_pg in payinPaymentGatewayId])
							if payoutPaymentGatewayId:
								third_party_integration.update(payoutPaymentGatewaysList=[ObjectId(each_payout_pg) for each_payout_pg in payoutPaymentGatewayId])
							flash("Site updated successfully","success")
							data_status["responseStatus"]=1
							return data_status
						else:
							flash("Site not found","danger")
							data_status["responseStatus"]=4
							return data_status
					except Exception as e:
						app.logger.error(traceback.format_exc())
						error = "Unable to update site details"
						flash(error, "error")
						data_status["responseStatus"]=4
						return data_status
				else:
					flash("Required fields are missing!!","warning")
					data_status["responseStatus"]=2
					return data_status
			else:
				print("(((((((((((((((((((((((((((((formerrors)))))))))))))))))))))))))))))",form.errors)
				data_status["result"]=form.errors
				return data_status
		else:
			flash("The staff member does not have permission to update Site.", "danger")
			data_status["responseStatus"]=4
			return data_status
	except Exception as e:
		app.logger.error(traceback.format_exc())
		error = "Unable to update SiteP details."
		flash(error, "error")
		data_status["responseStatus"]=4
		return data_status

 
 

@third_party_integrations.route("/get_sites_list", methods=["POST", "GET"])
@adminid_access_token_required
def get_sites_list():
	if not session.get("adminId"):
		return redirect("admin_login")

	sitesList = []
	transactionAPIsList = []
	payinEnableList = []
	payoutEnableList = []
	# paramList = []  # Initialize an empty list for parameters
	profilePagination=""
	snoCount=0
	

	permissionsList = check_permissions(session.get("adminId"),"thirdPartyIntegrationPermissions")
	if "view" in permissionsList:
		try:
			redirectTo = request.args.get("redirectTo", "Site")
			if redirectTo:
				redirectval = redirectTo
			else:
				redirectval = "Site"
				
			profilePage = request.args.get(get_page_parameter('profilePage'), type=int, default=1)
			per_page = 20
			start = (profilePage - 1) * per_page
			total_count = 0

			sites_queryset = ThirdPartyMerchants.objects(status__in=[0, 1]).order_by("-id") .skip(start).limit(per_page)
			site_dict = {}
			for each_site in sites_queryset:
				site_dict = {
					"id": str(each_site.id),
					"name": each_site.name,
					"ipAddress": each_site.ipAddress,
					"apiKey": each_site.apiKey,
					"secretKey": each_site.secretKey,  # Include secretKey if needed
					"enablePayin": each_site.enablePayin,
					"payinWebhook": each_site.payinWebhook,  # Include webhook for updates
					"enablePayout": each_site.enablePayout,
					"payoutWebhook": each_site.payoutWebhook,  # Include webhook for updates
					"payoutVAWebhook": each_site.payoutVAWebhook,  # Include webhook for updates
					"payoutValidationWebhook": each_site.payoutValidationWebhook,  # Include webhook for updates
					"payoutAlertsWebhook": each_site.payoutAlertsWebhook,  # Include webhook for updates
					"createdOn": each_site.createdOn.strftime("%d-%m-%Y %H:%M:%S %p"),
					"status": each_site.status,
				}
				if each_site.payinPaymentGatewaysList:
					site_dict["payinPaymentGatewaysList"]=[str(eachsite.id) for eachsite in each_site.payinPaymentGatewaysList]
					site_dict["payinNames"]=[str(eachsite.apiName) for eachsite in each_site.payinPaymentGatewaysList]
		 
					site_dict["payinNames"] = ', '.join(site_dict["payinNames"])
				else:
					site_dict["payinPaymentGatewaysList"]=[]
					site_dict["payinNames"]=""
					
				try:
					if each_site.trnIdentifier:
						site_dict["trnIdentifier"]=str(each_site.trnIdentifier)
					else:
						site_dict["trnIdentifier"]=""
				except Exception as e:
					site_dict["trnIdentifier"]=""

				if each_site.payoutPaymentGatewaysList:
					site_dict["payoutPaymentGatewaysList"]=[str(eachsite.id) for eachsite in each_site.payoutPaymentGatewaysList]
					site_dict["payoutNames"]=[str(eachsite.apiName) for eachsite in each_site.payoutPaymentGatewaysList]
		 
					site_dict["payoutNames"] = ', '.join(site_dict["payoutNames"])
				else:
					site_dict["payoutPaymentGatewaysList"]=[]
					site_dict["payoutNames"]=""

				if each_site.payinPaymentGatewayId:
					site_dict["payinPaymentGatewayId"]=str(each_site.payinPaymentGatewayId.id)
					site_dict["payinapiName"]=str(each_site.payinPaymentGatewayId.apiName)
				else:
					site_dict["payinPaymentGatewayId"]=""
					site_dict["payinapiName"]=""

				if each_site.payoutPaymentGatewayId:
					site_dict["payoutPaymentGatewayId"]=str(each_site.payoutPaymentGatewayId.id)
					site_dict["payoutapiName"]=str(each_site.payoutPaymentGatewayId.apiName)
				else:
					site_dict["payoutPaymentGatewayId"]=""
					site_dict["payoutapiName"]=""
				sitesList.append(site_dict)
			total_count=ThirdPartyMerchants.objects().count()
			# filters = Q(status__in=[0, 1])
			# sites_queryset = (
			#     ThirdPartyMerchants.objects()
			#     .filter(status=1)
			#     .order_by("-id")
			#     .only("id","name","ipAddress","apiKey","secretKey","enablePayin","payinWebhook","enablePayout","payoutWebhook","payoutVAWebhook","payoutValidationWebhook","payoutAlertsWebhook","createdOn","status")
			# )
			# total_count=ThirdPartyMerchants.objects(filters).count()
			# sitesList=list(sites_queryset)
			
			# print("(((((((((sitesList)))))))))",sitesList)
		  
			# Fetch payin and payout enable lists
			# payout_enable_queryset = TransactionAPI.objects(transactionType="Payout", status=1).order_by('-id')
			# for each_payout_enable in payout_enable_queryset:
			#     payoutDict = fetching_transaction_api_details(each_payout_enable)
			#     payoutEnableList.append(payoutDict)
			snoCount = start
			profilePagination = Pagination(profilePage=profilePage, total=total_count, page_parameter="profilePage", per_page=per_page, alignment="right", record_name="Site", href=f"?profilePage={{0}}")
		   
			payout_enable_queryset = (
				TransactionAPI.objects.filter(transactionType="Payout", status=1)
				.order_by("-id")
				.only("id", "apiName", "transactionType")
			)
			
			payoutEnableList=list(payout_enable_queryset)
			# print("((((((((payoutEnableList))))))))",payoutEnableList)
			# for api in payoutEnableList:
			#     print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++",api.apiName, api.id)
			
			# payin_enable_queryset = TransactionAPI.objects(transactionType="PaymentGateway", status=1).order_by('-id')
			# print("payin_enable_queryset)))))))))",payin_enable_queryset)
			# for each_payin_enable in payin_enable_queryset:
			#     payinDict = fetching_transaction_api_details(each_payin_enable)
				# payinEnableList.append(payinDict)
				
			payinEnableList = list(
				TransactionAPI.objects.filter(transactionType="PaymentGateway", status=1)
				.order_by("-id")
				.only("id", "apiName", "transactionType")
			)
			print("(((((((((((payinEnableList)))))))))))",payinEnableList)
			

			
			
			return render_template("super_admin_templates/sites_list.html",
				sitesList=sitesList,
				transactionAPIsList=transactionAPIsList,
				payinEnableList=payinEnableList,
				payoutEnableList=payoutEnableList,
				redirectval=redirectval,
				profilePagination=profilePagination,
				profilePage=profilePage,
				snoCount=snoCount
				# paramList=paramList
			)
		except Exception as e:
			app.logger.error(traceback.format_exc())
			error = "Unable to fetch site details!!"
			return render_template("super_admin_templates/sites_list.html", 
				error=error,
				sitesList=sitesList,
				transactionAPIsList=transactionAPIsList,
				payinEnableList=payinEnableList,
				redirectval=redirectval,
				payoutEnableList=payoutEnableList,
				profilePagination=profilePagination,
				profilePage=profilePage,
				snoCount=snoCount
				# paramList=paramList
			)
	else:
		flash("The staff member does not have permission to view Site Details!", "danger")
		return redirect(url_for("admin.dashboard"))
		
		


@third_party_integrations.route("/update_site_status", methods=["POST", "GET"])
@adminid_access_token_required
@csrf_protect
def update_site_status():
	if not session.get("adminId"):
		return redirect("admin_login")
	adminId = session.get("adminId")
	latitude = request.args.get("latitude", "")
	longitude = request.args.get("longitude", "")
	loginBrowser = request.headers.get("Sec-Ch-Ua")
	csrf_token = request.form.get("csrf_token")
	print(csrf_token,"((((((((((((((csrf_token))))))))))))))")
	
	if loginBrowser:
		loginBrowseData = loginBrowser.split(";")
		browser = loginBrowseData[0]
	else:
		loginBrowseData = request.headers.get('User-Agent').split(";")
		browser = loginBrowseData[0]

	client_ip = 0
	# Extracting client IP address
	if request.headers.getlist("X-Forwarded-For"):
		client_ip = request.headers.getlist("X-Forwarded-For")[0]
	else:
		client_ip = request.remote_addr

	actionDate = datetime.datetime.now()

	jsonData = request.form.to_dict(flat=True)

	existing_record = ""
	requestData = [existing_record]
	updatedrequestData = [jsonData]
	
	permissionsList = check_permissions(session.get("adminId"), "thirdPartyIntegrationPermissions")
	if "edit" in permissionsList:
		siteId = request.form.get("siteId", "")  # Get the site ID for updates
		profilePage = request.args.get("profilePage")
		if siteId:
			try:
				message=""
				site_queryset = ThirdPartyMerchants.objects(id=siteId,status__nin=[2]).first()
				existing_record = site_queryset.to_json()
			
				if site_queryset:
					admin_queryset = SuperAdmin.objects(id=adminId,status=1).first()
					if site_queryset.status == 0:
						site_queryset.update(status=1)
						flash("Site activated successfully","success")
						message=admin_queryset.userName+" "+site_queryset.name+" Site activated successfully!"

					elif site_queryset.status == 1:
						site_queryset.update(status=0)
						flash("Site deactivated successfully","success")
						message=admin_queryset.userName+" "+site_queryset.name+" Site deactivated successfully!"

					save_admin_log_table = save_admin_logs_data(adminId, None, None, "update_site_status", "updatestatus", actionDate, client_ip, browser, message, requestData, updatedrequestData,latitude,longitude)
					return redirect(url_for("third_party_integrations.get_sites_list",profilePage=profilePage))
				else:
					flash("Invalid site ID","danger")
					return redirect(url_for("third_party_integrations.get_sites_list",profilePage=profilePage))
			except Exception as e:
				app.logger.error(traceback.format_exc())
				return redirect(url_for("third_party_integrations.get_sites_list",profilePage=profilePage))
		else:
			return redirect(url_for("third_party_integrations.get_sites_list",profilePage=profilePage))
	else:
		flash("The staff member does not have permission to update site status.", "danger")
		return redirect(url_for("third_party_integrations.get_sites_list",profilePage=profilePage))

