from appservices.common.util import *

velocity_rule_engines = Blueprint("velocity_rule_engines",__name__)

@velocity_rule_engines.route("/create_velocity_rule_engine",methods=["POST","GET"])
def create_velocity_rule_engine():
    try:
        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()
        merchantsList = []
        paymentsModeList = []
        permissionsList = check_permissions(adminId,"velocityRuleEnginePermissions")
        if "add" in permissionsList:
            if request.method == "GET":
                merchants_queryset = Users.objects(status__nin=[2,3]).order_by("-id").all()
                for each_merchant in merchants_queryset:
                    velocity_rule_engine_queryset = VelocityRuleEngine.objects(userId=str(each_merchant.id)).first()
                    if not velocity_rule_engine_queryset:
                        merchantDict = fetching_user_details(each_merchant)
                        merchantsList.append(merchantDict)

                payment_modes_queryset = PaymentMode.objects(walletType="Payout",status__in=[0,1]).order_by("-id").all()
                for each_payment_mode in payment_modes_queryset:
                    payment_mode_data = fetching_payment_mode_details(each_payment_mode)
                    paymentsModeList.append(payment_mode_data)

                return render_template("super_admin_templates/create_velocity_rule_engine.html",merchantsList=merchantsList,paymentsModeList=paymentsModeList)

            if request.method == "POST":
                userId = request.form.get("userId","")
                minTxnAmount = request.form.get("minTxnAmount",0)
                maxTxnAmount = request.form.get("maxTxnAmount",0)
                maxTxnsPerMinute = request.form.get("maxTxnsPerMinute",0)
                maxTxnsPerBenificiary = request.form.get("maxTxnsPerBenificiary",0)
                noOfFailsPerInsuffcientBalance = request.form.get("noOfFailsPerInsuffcientBalance",0)
                noOfFailsPerLoadFunds = request.form.get("noOfFailsPerLoadFunds",0)
                maxTxnsSameAmountPerHour = request.form.get("maxTxnsSameAmountPerHour",0)
                noOfFailsPerBenificiary = request.form.get("noOfFailsPerBenificiary",0)

                # Fetching lists from the form
                paymentModeListField = request.form.getlist("paymentModeId[]")
                startTimeListField = request.form.getlist("startTime[]")
                endTimeListField = request.form.getlist("endTime[]")
                minAmountListField = request.form.getlist("minAmount[]")
                maxAmountListField = request.form.getlist("maxAmount[]")

                jsonData = request.form.to_dict(flat=True)
                requestData = [jsonData]
                updatedrequestData = [jsonData]

                print(request.form, "((((((((((Create Velocity FORM))))))))))")
           

                paymentModeLimits = []

                for i in range(len(startTimeListField)):
                    finalDict = {
                        "paymentModeId": paymentModeListField[i] if i < len(paymentModeListField) else None,
                        "startTime": startTimeListField[i],
                        "endTime": endTimeListField[i],
                        "minAmount": minAmountListField[i] if i < len(minAmountListField) else None,
                        "maxAmount": maxAmountListField[i] if i < len(maxAmountListField) else None
                    }
                    paymentModeLimits.append(finalDict)

                print(paymentModeLimits,"(((((((((((paymentModeLimits)))))))))))")

                if userId and minTxnAmount and maxTxnAmount and maxTxnsPerMinute and maxTxnsPerBenificiary and noOfFailsPerInsuffcientBalance and noOfFailsPerLoadFunds and maxTxnsSameAmountPerHour and noOfFailsPerBenificiary and paymentModeLimits:
                    try:
                        admin_queryset = SuperAdmin.objects(id=adminId,status=1).first()
                        user_queryset = Users.objects(id=userId,status=1).first()
                        if admin_queryset:
                            message=admin_queryset.userName+" "+user_queryset.fullName+" Merchant Velocity rule engines are created by admin successfully!"
                            save_admin_log_table = save_admin_logs_data(adminId,None,None,"create_velocity_rule_engine","create",actionDate,client_ip,browser,message,requestData,updatedrequestData) 
                        create_velocity_rule_table = VelocityRuleEngine(
                            adminId=adminId,
                            userId = userId,
                            minTxnAmount = minTxnAmount,
                            maxTxnAmount = maxTxnAmount,
                            maxTxnsPerMinute = maxTxnsPerMinute,
                            maxTxnsPerBenificiary = maxTxnsPerBenificiary,
                            noOfFailsPerInsuffcientBalance = noOfFailsPerInsuffcientBalance,
                            noOfFailsPerLoadFunds = noOfFailsPerLoadFunds,
                            maxTxnsSameAmountPerHour = maxTxnsSameAmountPerHour,
                            noOfFailsPerBenificiary = noOfFailsPerBenificiary,
                            paymentModeLimits = paymentModeLimits,
                            createdOn = datetime.datetime.now(),
                            status = 1,
                            )
                        save_table = create_velocity_rule_table.save()

                        flash("Velocity rule engine created successfully!")
                        return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                    except Exception as e:
                        flash("Unable to create velocity rule engine details!!")
                        app.logger.error(traceback.format_exc())
                        return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                else:
                    flash("Required fields are missing!!")
                    return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
        else:
            flash("Staff member does not have given create velocity rule engine permissions!!")
            return render_template("super_admin_templates/create_velocity_rule_engine.html")
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to create velocity rule engine details!!"
        return render_template("super_admin_templates/velocity_rule_engines_list.html",error=error)


def fetching_velocity_rule_engine_details(each_velocity):
    velocityRuleDict = {}
    try:
        velocityRuleDict = {
        "id":str(each_velocity.id),
        "userId":str(each_velocity.userId.id),
        "userName":each_velocity.userId.fullName,
        "minTxnAmount":each_velocity.minTxnAmount,
        "maxTxnAmount":each_velocity.maxTxnAmount,
        "maxTxnsPerMinute":each_velocity.maxTxnsPerMinute,
        "maxTxnsPerBenificiary":each_velocity.maxTxnsPerBenificiary,
        "noOfFailsPerInsuffcientBalance":each_velocity.noOfFailsPerInsuffcientBalance,
        "noOfFailsPerLoadFunds":each_velocity.noOfFailsPerLoadFunds,
        "maxTxnsSameAmountPerHour":each_velocity.maxTxnsSameAmountPerHour,
        "noOfFailsPerBenificiary":each_velocity.noOfFailsPerBenificiary,
        "createdOn":each_velocity.createdOn.astimezone(ist_timezone).strftime("%d-%m-%Y %I:%M %p"),
        "status":each_velocity.status
        }
        paymentModeLimits = []
        if each_velocity.paymentModeLimits:
            for each_payment in each_velocity.paymentModeLimits:
                payment_mode_queryset = PaymentMode.objects(id=str(each_payment.get('paymentModeId'))).first()
                paymentModeDict = {
                "paymentModeId":each_payment.get('paymentModeId'),
                "paymentMode":payment_mode_queryset.paymentMode,
                "startTime":each_payment.get('startTime'),
                "endTime":each_payment.get('endTime'),
                "minAmount":each_payment.get('minAmount'),
                "maxAmount":each_payment.get('maxAmount')
                }
                paymentModeLimits.append(paymentModeDict)
            velocityRuleDict["paymentModeLimits"]=paymentModeLimits
        else:
            velocityRuleDict["paymentModeLimits"]=[]
        if each_velocity.status == 1:
            velocityRuleDict["actionText"]="Active"
        else:
            velocityRuleDict["actionText"]="Deactive"
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return velocityRuleDict


@velocity_rule_engines.route("/view_all_velocity_rule_engines",methods=["POST","GET"])
def view_all_velocity_rule_engines():
    if not session.get("adminId"):
        return redirect("admin_login")
    velocityRulesList = []
    
    adminId = session.get("adminId")

    permissionsList = check_permissions(adminId,"velocityRuleEnginePermissions")
    if "view" in permissionsList:
        try:
            redirectTo = request.args.get("redirectTo","velocity")
            if redirectTo:
                redirectval = redirectTo
            else:
                redirectval = "velocity"
            search_element = request.form.get("search_element","")


            velocity_rule_engine_queryset = VelocityRuleEngine.objects(status__in=[0,1]).order_by("-id").all()

            for each_velocity in velocity_rule_engine_queryset:
                velocityRuleDict = fetching_velocity_rule_engine_details(each_velocity)
                velocityRulesList.append(velocityRuleDict)

            return render_template("super_admin_templates/velocity_rule_engines_list.html",
                velocityRulesList=velocityRulesList,
                redirectval=redirectval,
                search_element=search_element
                )
        except Exception as e:
            app.logger.error(traceback.format_exc())
            error = "Unable to fetch velocity rule engine details!!"
            return render_template("super_admin_templates/velocity_rule_engines_list.html", 
                error=error,
                velocityRulesList=velocityRulesList,
                search_element=search_element
                )
    else:
        flash("Staff member does not have given view velocity rule engine permissions!!")
        return render_template("super_admin_templates/velocity_rule_engines_list.html")

@velocity_rule_engines.route("/update_velocity_rule_engine_status",methods=["POST","GET"])
def update_velocity_rule_engine_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"),"velocityRuleEnginePermissions")
    if "edit" in permissionsList:
        velocityId = request.args.get("velocityId","")

        if velocityId:
            try:
                velocity_rule_engine_queryset = VelocityRuleEngine.objects(id=velocityId).first()
                existing_record = velocity_rule_engine_queryset.to_json()
                requestData = [existing_record]
                if velocity_rule_engine_queryset:
                    if velocity_rule_engine_queryset.status == 0:
                        velocity_rule_engine_queryset.update(status=1)
                        flash("Velocity rule engine activated successfully!")
                        message=velocity_rule_engine_queryset.adminId.userName+" "+userId.fullName+" Velocity rule engine activated successfully!"
                    elif velocity_rule_engine_queryset.status == 1:
                        velocity_rule_engine_queryset.update(status=0)
                        flash("Velocity rule engine deactivated successfully!")
                        message=velocity_rule_engine_queryset.adminId.userName+" "+userId.fullName+" Velocity rule engine deactivated successfully!"
                    save_admin_log_table = save_admin_logs_data(adminId,None,None,"update_velocity_rule_engine_status","updatestatus",actionDate,client_ip,browser,message,requestData,updatedrequestData)
                    return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
            except Exception as e:
                app.logger.error(traceback.format_exc())
                return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
        else:
            flash("Required field is missing!!")
            return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
    else:
        flash("Staff member does not have given update status velocity rule engine permissions!!")
        return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))


@velocity_rule_engines.route("/update_velocity_rule_engine",methods=["POST","GET"])
def update_velocity_rule_engine():
    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()
    permissionsList = check_permissions(session.get("adminId"),"velocityRuleEnginePermissions")
    if "edit" in permissionsList:
        velocityId = request.args.get("velocityId","")

        paymentsModeList = []
        checkPaymentsModesList = []

        try:
            if request.method == "GET":
                payment_modes_queryset = PaymentMode.objects(walletType="Payout", status__in=[0, 1]).order_by("-id").all()
                paymentsModeList = [fetching_payment_mode_details(each_payment_mode) for each_payment_mode in payment_modes_queryset]

                velocity_rule_engine_queryset = VelocityRuleEngine.objects(id=velocityId, status__in=[0, 1]).first()
                if not velocity_rule_engine_queryset:
                    flash("Invalid velocity id!!")
                    return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))

                velocityRuleDict = fetching_velocity_rule_engine_details(velocity_rule_engine_queryset)

                checkPaymentsModesList = []
                payment_mode_ids = set()

                for each_payment_dict in velocity_rule_engine_queryset.paymentModeLimits:
                    payment_mode_queryset = PaymentMode.objects(id=str(each_payment_dict.get("paymentModeId"))).first()
                    paymentModeDict = {
                        "paymentModeId": each_payment_dict.get("paymentModeId"),
                        "startTime": each_payment_dict.get("startTime"),
                        "endTime": each_payment_dict.get("endTime"),
                        "minAmount": each_payment_dict.get("minAmount"),
                        "maxAmount": each_payment_dict.get("maxAmount"),
                        "paymentMode": payment_mode_queryset.paymentMode,
                        "checkFlag": True
                    }
                    checkPaymentsModesList.append(paymentModeDict)
                    payment_mode_ids.add(each_payment_dict.get("paymentModeId"))

                for each_payment_mode in payment_modes_queryset:
                    if str(each_payment_mode.id) not in payment_mode_ids:
                        payment_mode_data = fetching_payment_mode_details(each_payment_mode)
                        payment_mode_data["checkFlag"] = False
                        checkPaymentsModesList.append(payment_mode_data)

                return render_template("super_admin_templates/update_velocity_rule_engine.html", velocityRuleDict=velocityRuleDict, paymentsModeList=paymentsModeList, checkPaymentsModesList=checkPaymentsModesList)

            if request.method == "POST":
                minTxnAmount = request.form.get("minTxnAmount",0)
                maxTxnAmount = request.form.get("maxTxnAmount",0)
                maxTxnsPerMinute = request.form.get("maxTxnsPerMinute",0)
                maxTxnsPerBenificiary = request.form.get("maxTxnsPerBenificiary",0)
                noOfFailsPerInsuffcientBalance = request.form.get("noOfFailsPerInsuffcientBalance",0)
                noOfFailsPerLoadFunds = request.form.get("noOfFailsPerLoadFunds",0)
                maxTxnsSameAmountPerHour = request.form.get("maxTxnsSameAmountPerHour",0)
                noOfFailsPerBenificiary = request.form.get("noOfFailsPerBenificiary",0)

                # Fetching lists from the form
                paymentModeListField = request.form.getlist("paymentModeId[]")
                startTimeListField = request.form.getlist("startTime[]")
                endTimeListField = request.form.getlist("endTime[]")
                minAmountListField = request.form.getlist("minAmount[]")
                maxAmountListField = request.form.getlist("maxAmount[]")
                jsonData = request.form.to_dict(flat=True)

                print(request.form, "((((((((((Update Velocity FORM))))))))))")

                paymentModeLimits = []

                for i in range(len(startTimeListField)):
                    finalDict = {
                        "paymentModeId": paymentModeListField[i] if i < len(paymentModeListField) else None,
                        "startTime": startTimeListField[i],
                        "endTime": endTimeListField[i],
                        "minAmount": minAmountListField[i] if i < len(minAmountListField) else None,
                        "maxAmount": maxAmountListField[i] if i < len(maxAmountListField) else None
                    }
                    paymentModeLimits.append(finalDict)

                print(paymentModeLimits,"(((((((((((paymentModeLimits)))))))))))")

                if velocityId:
                    try:
                        existing_record = ""
                        velocity_rule_engine_queryset = VelocityRuleEngine.objects(id=velocityId).first()
                        existing_record = velocity_rule_engine_queryset.to_json()
                        message=velocity_rule_engine_queryset.adminId.userName+" "+user_queryset.fullName+" Merchant Velocity rule engines updated successfully!"
                        requestData=[existing_record]
                        updatedrequestData=[jsonData]
                        save_admin_log_table = save_admin_logs_data(adminId,None,None,"update_master_ifsc_bank","update",actionDate,client_ip,browser,message,requestData,updatedrequestData) 

                        if velocity_rule_engine_queryset:
                            velocity_rule_engine_queryset.update(
                                minTxnAmount = minTxnAmount,
                                maxTxnAmount = maxTxnAmount,
                                maxTxnsPerMinute = maxTxnsPerMinute,
                                noOfFailsPerInsuffcientBalance = noOfFailsPerInsuffcientBalance,
                                maxTxnsPerBenificiary = maxTxnsPerBenificiary,
                                noOfFailsPerLoadFunds = noOfFailsPerLoadFunds,
                                maxTxnsSameAmountPerHour = maxTxnsSameAmountPerHour,
                                noOfFailsPerBenificiary = noOfFailsPerBenificiary,
                                paymentModeLimits=paymentModeLimits
                                )

                            flash("Velocity rule engine updated successfully!")
                            return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                        else:
                            flash("Invaild velocity id!!")
                            return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                    except Exception as e:
                        app.logger.error(traceback.format_exc())
                        return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
                else:
                    flash("Required field is missing!!")
                    return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
    else:
        flash("Staff member does not have given update velocity rule engine permissions!!")
        return redirect(url_for("velocity_rule_engines.view_all_velocity_rule_engines"))
