from appservices.common.util import *

third_party_integrations = Blueprint("third_party_integrations",__name__)

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

        if request.method == "POST":
            # 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.get("payinPaymentGatewayId", "")
            payinWebhook = request.form.get("payinWebhook", "")
            enablePayout = request.form.get("enablePayout",False)
            payoutPaymentGatewayId = request.form.get("payinPaymentGatewayId", "")
            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")
            
            apiKey = random_alphanumeric_generate(12)
            secretKey = str(secrets.token_hex(12))


            if not enablePayin:
                payinPaymentGatewayId = None
                payinWebhook = ""

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

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

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

            if name and ipAddress and apiKey and secretKey:
                try:
                    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!")
                    return redirect(url_for("third_party_integrations.get_sites_list"))  # Adjust redirect
                except Exception as e:
                    flash("Unable to save site details!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("third_party_integrations.get_sites_list"))  # Adjust redirect
            else:
                flash("Required fields are missing!")
                return redirect(url_for("third_party_integrations.get_sites_list"))  # Adjust redirect
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to save site details!"
        return render_template("super_admin_templates/sites_list.html", error=error)  # Adjust template


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

        # Retrieve form data
        siteId = request.args.get("siteId","")  # Get the site ID for updates
        name = request.form.get("name", "")
        ipAddress = request.form.get("ipAddress", "")
        enablePayin = request.form.get("enablePayin",False)
        payinPaymentGatewayId = request.form.get("payinPaymentGatewayId", "")
        trnIdentifier = request.form.get("trnIdentifier", "")
        payinWebhook = request.form.get("payinWebhook", "")
        enablePayout = request.form.get("enablePayout",False)
        payoutPaymentGatewayId = request.form.get("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")

        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()
                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 payinPaymentGatewaysList:
                        third_party_integration.update(payinPaymentGatewaysList=[ObjectId(each_payin_pg) for each_payin_pg in payinPaymentGatewaysList])
                    if payoutPaymentGatewaysList:
                        third_party_integration.update(payoutPaymentGatewaysList=[ObjectId(each_payout_pg) for each_payout_pg in payoutPaymentGatewaysList])
                    flash("Site updated successfully!")
                else:
                    flash("Site not found!")
            except Exception as e:
                flash("Unable to update site details!")
                app.logger.error(traceback.format_exc())
        else:
            flash("Required fields are missing!")
        
        return redirect(url_for("third_party_integrations.get_sites_list"))
    
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to update site details!"
        return render_template("super_admin_templates/sites_list.html", error=error)



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

    sitesList = []
    transactionAPIsList = []
    payinEnableList = []
    payoutEnableList = []
    # paramList = []  # Initialize an empty list for parameters


    try:
        redirectTo = request.args.get("redirectTo", "Site")

        sites_queryset = ThirdPartyMerchants.objects(status__in=[0, 1]).order_by("-id")
        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)

        # 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)

        payin_enable_queryset = TransactionAPI.objects(transactionType="PaymentGateway", status=1).order_by('-id')
        for each_payin_enable in payin_enable_queryset:
            payinDict = fetching_transaction_api_details(each_payin_enable)
            payinEnableList.append(payinDict)

        return render_template("super_admin_templates/sites_list.html",
            sitesList=sitesList,
            # transactionAPIsList=transactionAPIsList,
            payinEnableList=payinEnableList,
            payoutEnableList=payoutEnableList,
            redirectval=redirectTo,
            # 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,
            payoutEnableList=payoutEnableList,
            # paramList=paramList
        )


@third_party_integrations.route("/update_site_status", methods=["POST", "GET"])
def update_site_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    adminId = session.get("adminId")
    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()

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

    existing_record = ""
    updatedrequestData = [jsonData]
    permissionsList = check_permissions(session.get("adminId"), "sitePermissions")
    
    # if "edit" in permissionsList:
    siteId = request.form.get("siteId", "")  # Get the site ID for updates
    if siteId:
        try:
            site_queryset = ThirdPartyMerchants.objects(id=ObjectId(siteId)).first()
            existing_record = site_queryset.to_json()
            requestData = [existing_record]

            if site_queryset:
                if site_queryset.status == 0:
                    site_queryset.update(status=1)
                    flash("Site activated successfully!")
                    message = f"{site_queryset.name} activated successfully!"

                elif site_queryset.status == 1:
                    site_queryset.update(status=0)
                    flash("Site deactivated successfully!")
                    message = f"{site_queryset.name} deactivated successfully!"
                
                save_admin_log_table = save_admin_logs_data(adminId, None, None, "update_site_status", "updatestatus", actionDate, client_ip, browser, message, requestData, updatedrequestData)

                return redirect(url_for("third_party_integrations.get_sites_list"))
            else:
                flash("Invalid site ID!")
                return redirect(url_for("third_party_integrations.get_sites_list"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("third_party_integrations.get_sites_list"))
    else:
        return redirect(url_for("third_party_integrations.get_sites_list"))
    # else:
    #     flash("Staff member does not have given update status permissions!")
    #     return redirect(url_for("third_party_integrations.get_sites_list"))
