from appservices.common.util import *

switch_master = Blueprint("switch_master",__name__)

# Add Switch Type
@switch_master.route("/add_switch_type",methods=["POST","GET"])
def add_switch_type():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        
        if request.method == "POST":
            switchType = request.form.get("switchType","")
            priority = request.form.get("priority","")
            if switchType and priority:
                try:
                    switch_table = SwitchTypes(
                        adminId = adminId,
                        switchType = switchType,
                        priority = priority,
                        createdOn = datetime.datetime.now(),
                        status = 1,
                        )
                    save_table = switch_table.save()
                    switchTypeId = str(switch_table.id)
                    flash("Switch type saved successfully!")
                    return redirect(url_for("switch_master.switch_masters_list"))
                except Exception as e:
                    flash("Unable to save switch type!!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("switch_master.switch_masters_list"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("switch_master.switch_masters_list"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to save swicth type!!"
        return render_template("super_admin_templates/switch_masters_list.html",error=error)

def fetching_switch_type_details(switch_type_queryset):
    switch_type_dict = {}
    try:
        switch_type_dict={
        "id":str(switch_type_queryset.id),
        "switchType":switch_type_queryset.switchType,
        "priority":switch_type_queryset.priority,
        }
        if switch_type_queryset.status==1:
            switch_type_dict["actionText"] = "Active"
        else:
            switch_type_dict["actionText"] = "Deactive"
        if switch_type_queryset.createdOn:
            switch_type_dict["createdOn"] = switch_type_queryset.createdOn.strftime("%m-%d-%Y")
        else:
            switch_type_dict["createdOn"] = ""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return switch_type_dict

# View All swicth masters list
@switch_master.route("/switch_masters_list",methods=["POST","GET"])
def switch_masters_list():
    if not session.get("adminId"):
        return redirect("admin_login")
    adminId = session.get("adminId")
    switchTypesList = []
    usersList = []
    operatorsList = []
    transactionAPIsList = []
    operatorsSwitchingList = []
    amountsSwitchingList = []
    statesList = []
    try:
        redirectto = request.args.get('redirectto','Switchtype')
        if redirectto:
            redirectval=redirectto
        else:
            redirectval="Switchtype"

        switch_type_search_element = request.args.get('switch_type_search_element','')
        operator_switch_search_element = request.args.get('operator_switch_search_element','')
        amount_switch_search_element = request.args.get('amount_switch_search_element','')

        ###################################### Common Lists ########################################
        users_queryset = Users.objects(status__in=[0,1]).order_by('-id').all()
        for each_user in users_queryset:
            userDict = fetching_user_details(each_user)
            usersList.append(userDict)

        operators_queryset = Operators.objects(status__in=[0,1]).order_by('-id').all()
        for each_operator in operators_queryset:
            operator_dict = fetching_operator_details(each_operator)
            operatorsList.append(operator_dict)

        states_queryset = States.objects(status__in=[0,1]).order_by("stateName").all()
        for each_state in states_queryset:
            state_dict = fetching_states_details(each_state)
            statesList.append(state_dict)

        transaction_API_queryset = TransactionAPI.objects(status__in=[0,1]).order_by('-id').all()
        for each_transaction_api in transaction_API_queryset:
            service_grouping_dict = {
            "id":str(each_transaction_api.id),
            "apiName":each_transaction_api.apiName
            }
            transactionAPIsList.append(service_grouping_dict)

        ###################################### Switchtypes Data ########################################            
        switch_types_queryset = SwitchTypes.objects(adminId=adminId,status__in=[0,1]).order_by("-id")
        if switch_type_search_element:
            switch_types_queryset = switch_types_queryset.filter(Q(switchType__icontains=switch_type_search_element))

        # 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 = switch_types_queryset.count()

        start = (page - 1) * per_page
        end = min(start + per_page, total_count)

        total_switch_types = switch_types_queryset[start:end]

        for each_switch_type in total_switch_types:
            switch_type_dict = fetching_switch_type_details(each_switch_type)
            switchTypesList.append(switch_type_dict)

        # Pagination object for rendering pagination controls in the template
        pagination = Pagination(page=page, total=total_count, per_page=per_page, alignment="right")
        
        ############################### OperatorSwitching Data #########################################
        operators_switching_queryset = OperatorSwitching.objects(status__in=[0,1]).order_by('-id').all()
        if operator_switch_search_element:
            operators_switching_queryset = operators_switching_queryset.filter(Q(apiCount=switch_type_search_element))

        # Get the current page from the query parameters
        pageOperatorSwitching = request.args.get(get_page_parameter(), type=int, default=1)
        perPageOperatorSwitching = 20  # Number of items per page

        # Query the database for the current page's data
        total_operator_switching_count = operators_switching_queryset.count()

        startOperatorSwitching = (pageOperatorSwitching - 1) * perPageOperatorSwitching
        endOperatorSwitching = min(startOperatorSwitching + perPageOperatorSwitching, total_operator_switching_count)

        totalOperatorSwitching = operators_switching_queryset[startOperatorSwitching:endOperatorSwitching]

        for each_operator_switching in totalOperatorSwitching:
            operator_switching_dict = fetching_operator_switching_details(each_operator_switching)
            operatorsSwitchingList.append(operator_switching_dict)

        # Pagination object for rendering pagination controls in the template
        operatorSwitchingPagination = Pagination(page=pageOperatorSwitching, 
            total=total_operator_switching_count, per_page=perPageOperatorSwitching, 
            alignment="right",page_parameter="Operatorswitching",href="switch_masters_list?redirectto=Operatorswitching&pageOperatorSwitching={0}")

        ############################### Amount Switching Data #########################################
        amount_switching_queryset = AmountSwitching.objects(status__in=[0,1]).order_by('-id').all()
        if amount_switch_search_element:
            amount_switching_queryset = amount_switching_queryset.filter(Q(amount=amount_switch_search_element))

        # Get the current page from the query parameters
        pageAmountSwitching = request.args.get(get_page_parameter(), type=int, default=1)
        perPageAmountSwitching = 20  # Number of items per page

        # Query the database for the current page's data
        total_amount_switching_count = amount_switching_queryset.count()

        startAmountSwitching = (pageAmountSwitching - 1) * perPageAmountSwitching
        endAmountSwitching = min(startAmountSwitching + perPageAmountSwitching, total_amount_switching_count)

        totalAmountSwitchings = amount_switching_queryset[startAmountSwitching:endAmountSwitching]

        for each_amount_switching in totalAmountSwitchings:
            amount_switching_dict = fetching_amount_switching_details(each_amount_switching)
            amountsSwitchingList.append(amount_switching_dict)

        # Pagination object for rendering pagination controls in the template
        amountSwitchingPagination = Pagination(page=pageAmountSwitching, 
            total=total_amount_switching_count, per_page=perPageAmountSwitching, 
            alignment="right",page_parameter="Amountswitching",href="switch_masters_list?redirectto=Amountswitching&pageAmountSwitching={0}")

        return render_template("super_admin_templates/switch_masters_list.html",
            usersList=usersList,
            operatorsList=operatorsList,
            statesList=statesList,
            operatorsSwitchingList=operatorsSwitchingList,
            transactionAPIsList=transactionAPIsList,
            switchTypesList=switchTypesList,
            amountsSwitchingList=amountsSwitchingList,
            switch_type_search_element=switch_type_search_element,
            pagination=pagination,
            operatorSwitchingPagination=operatorSwitchingPagination,
            amountSwitchingPagination=amountSwitchingPagination,
            redirectval=redirectval
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to fetch switch type details!!"
        return render_template("super_admin_templates/switch_masters_list.html",
            usersList=usersList,
            operatorsList=operatorsList,
            statesList=statesList,
            operatorsSwitchingList=operatorsSwitchingList,
            transactionAPIsList=transactionAPIsList,
            switchTypesList=switchTypesList,
            amountsSwitchingList=amountsSwitchingList,
            switch_type_search_element=switch_type_search_element,
            operator_switch_search_element=operator_switch_search_element,
            pagination=pagination,
            operatorSwitchingPagination=operatorSwitchingPagination,
            redirectval=redirectval
            )
# Update switch type status
@switch_master.route("/update_switch_type_status",methods=["POST","GET"])
def update_switch_type_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    switchTypeId = request.args.get("switchTypeId","")
    if switchTypeId:
        try:
            switch_type_queryset = SwitchTypes.objects(id=switchTypeId, status__nin=[2]).first()

            if switch_type_queryset:
                if switch_type_queryset.status == 0:
                    switch_type_queryset.update(status=1)
                    flash("Switch type activated successfully!")
                elif switch_type_queryset.status == 1:
                    switch_type_queryset.update(status=0)
                    flash("Switch type deactivated successfully!")
                return redirect(url_for("switch_master.switch_masters_list"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("switch_master.switch_masters_list"))
    else:
        return redirect(url_for("switch_master.switch_masters_list"))


# Delete switch type
@switch_master.route("/delete_switch_type",methods=["GET"])
def delete_switch_type():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        if request.method == "GET":
            switchTypeId = request.args.get("switchTypeId","")
            switch_type_queryset = SwitchTypes.objects(id=switchTypeId,status__in=[0,1]).first()
            if switch_type_queryset:
                switch_type_queryset.update(status=2)
                flash("Switch type deleted successfully!")
                return redirect(url_for("switch_master.switch_masters_list"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete switch type!!")
        return redirect(url_for("switch_master.switch_masters_list"))

# Update Master Type
@switch_master.route("/update_master_type",methods=["POST","GET"])
def update_master_type():
    if not session.get("adminId"):
        return redirect("admin_login")
    try:
        switchTypeId = request.args.get("switchTypeId","")
        if request.method == "POST":
            switchType = request.form.get("switchType","")
            priority = request.form.get("priority","")

        if switchType and priority:
            try:
                switch_types_queryset = SwitchTypes.objects(id=switchTypeId).first()
                if switch_types_queryset:
                    switch_types_queryset.update(
                        switchType = switchType,
                        priority = priority,
                        )
                    flash("Switch type updated successfully!")
                    return redirect(url_for("switch_master.switch_masters_list"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("switch_master.switch_masters_list"))
            except Exception as e:
                app.logger.error(traceback.format_exc())
                flash("Unable to update switch type!!")
                return redirect(url_for("switch_master.switch_masters_list"))
        else:
            flash("Required fields are missing!!")
            return redirect(url_for("switch_master.switch_masters_list"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to update switch type!!")


# # View single switch type
# @switch_master.route("/view_single_switch_type",methods=["POST","GET"])
# def view_single_switch_type():
#     if not session.get("adminId"):
#         return redirect("admin_login")
#     switchTypeId = request.args.get("switchTypeId","")
#     if switchTypeId:
#         try:
#             switch_type_queryset = SwitchTypes.objects(id=switchTypeId, status__nin=[2]).first()

#             if switch_type_queryset:
#                 switch_type_data = fetching_switch_type_details(switch_type_queryset)
#                 return render_template("super_admin_templates/view_single_switch_type.html",switch_type_dict=switch_type_dict)
#             else:
#                 flash("Invaild id!!")
#                 return redirect(url_for("switch_master.switch_masters_list"))


@switch_master.route("/add_operator_switch",methods=["POST","GET"])
def add_operator_switch():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        
        if request.method == "POST":
            userId = request.form.get("userId","")
            operatorId = request.form.get("operatorId","")
            apiCount = request.form.get("apiCount",0)
            apiId1 = request.form.get("apiId1","")
            apiId2 = request.form.get("apiId2","")
            apiId3 = request.form.get("apiId3","")
            apiId4 = request.form.get("apiId4","")
            apiId5 = request.form.get("apiId5","")
            apiId6 = request.form.get("apiId6","")
            apiId7 = request.form.get("apiId7","")

            if userId and operatorId and apiCount and apiId1:
                try:
                    switch_operator_table = OperatorSwitching(
                        adminId = adminId,
                        userId = userId,
                        operatorId = operatorId,
                        apiCount = apiCount,
                        apiId1 = apiId1,
                        createdOn = datetime.datetime.now(),
                        status = 1,
                        )
                    save_table = switch_operator_table.save()
                    if apiId2 == "":
                        save_table.update(apiId2 = None)
                    else:
                        save_table.update(apiId2 = ObjectId(apiId2))

                    if apiId3 == "":
                        save_table.update(apiId3 = None)
                    else:
                        save_table.update(apiId3 = ObjectId(apiId3))

                    if apiId4 == "":
                        save_table.update(apiId4 = None)
                    else:
                        save_table.update(apiId4 = ObjectId(apiId4))

                    if apiId5 == "":
                        save_table.update(apiId5 = None)
                    else:
                        save_table.update(apiId5 = ObjectId(apiId5))

                    if apiId6 == "":
                        save_table.update(apiId6 = None)
                    else:
                        save_table.update(apiId6 = ObjectId(apiId6))

                    if apiId7 == "":
                        save_table.update(apiId7 = None)
                    else:
                        save_table.update(apiId7 = ObjectId(apiId7))
                    flash("Operator switching saved successfully!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
                except Exception as e:
                    flash("Unable to save operator switching!!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to save operator switching!!"
        return render_template("super_admin_templates/switch_masters_list.html",error=error)

def fetching_operator_switching_details(operator_switching_queryset):
    operator_switching_dict = {}
    try:
        operator_switching_dict={
        "id":str(operator_switching_queryset.id),
        "userId":str(operator_switching_queryset.userId.id),
        "operatorId":str(operator_switching_queryset.operatorId.id),
        "apiId1":str(operator_switching_queryset.apiId1.id),
        "apiId1Name":operator_switching_queryset.apiId1.apiName,
        "operatorName":operator_switching_queryset.operatorId.operatorName,
        "userName":operator_switching_queryset.userId.fullName,
        "apiCount":operator_switching_queryset.apiCount
        }
        if operator_switching_queryset.apiId2:
            operator_switching_dict["apiId2"] = str(operator_switching_queryset.apiId2.id)
            operator_switching_dict["apiId2Name"] = operator_switching_queryset.apiId2.apiName
        else:
            operator_switching_dict["apiId2"] = ""
            operator_switching_dict["apiId2Name"] = ""

        if operator_switching_queryset.apiId3:
            operator_switching_dict["apiId3"] = str(operator_switching_queryset.apiId3.id)
            operator_switching_dict["apiId3Name"] = operator_switching_queryset.apiId3.apiName
        else:
            operator_switching_dict["apiId3"] = ""
            operator_switching_dict["apiId3Name"] = ""

        if operator_switching_queryset.apiId4:
            operator_switching_dict["apiId4"] = str(operator_switching_queryset.apiId4.id)
            operator_switching_dict["apiId4Name"] = operator_switching_queryset.apiId4.apiName
        else:
            operator_switching_dict["apiId4"] = ""
            operator_switching_dict["apiId4Name"] = ""

        if operator_switching_queryset.apiId5:
            operator_switching_dict["apiId5"] = str(operator_switching_queryset.apiId5.id)
            operator_switching_dict["apiId5Name"] = operator_switching_queryset.apiId5.apiName
        else:
            operator_switching_dict["apiId5"] = ""
            operator_switching_dict["apiId5Name"] = ""

        if operator_switching_queryset.apiId6:
            operator_switching_dict["apiId6"] = str(operator_switching_queryset.apiId6.id)
            operator_switching_dict["apiId6Name"] = operator_switching_queryset.apiId6.apiName
        else:
            operator_switching_dict["apiId6"] = ""
            operator_switching_dict["apiId6Name"] = ""

        if operator_switching_queryset.apiId7:
            operator_switching_dict["apiId7"] = str(operator_switching_queryset.apiId7.id)
            operator_switching_dict["apiId7Name"] = operator_switching_queryset.apiId7.apiName
        else:
            operator_switching_dict["apiId7"] = ""
            operator_switching_dict["apiId7Name"] = ""

        if operator_switching_queryset.status==1:
            operator_switching_dict["actionText"] = "Active"
        else:
            operator_switching_dict["actionText"] = "Deactive"
        if operator_switching_queryset.createdOn:
            operator_switching_dict["createdOn"] = operator_switching_queryset.createdOn.strftime("%m-%d-%Y")
        else:
            operator_switching_dict["createdOn"] = ""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return operator_switching_dict


@switch_master.route("/update_operator_switching_status",methods=["POST","GET"])
def update_operator_switching_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    operatorSwitchingId = request.args.get("operatorSwitchingId","")
    if operatorSwitchingId:
        try:
            operator_switching_queryset = OperatorSwitching.objects(id=operatorSwitchingId, status__nin=[2]).first()
            if operator_switching_queryset:
                if operator_switching_queryset.status == 0:
                    operator_switching_queryset.update(status=1)
                    flash("Operator switching activated successfully!")
                elif operator_switching_queryset.status == 1:
                    operator_switching_queryset.update(status=0)
                    flash("Operator switching deactivated successfully!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
    else:
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))


@switch_master.route("/delete_operator_switching",methods=["GET"])
def delete_operator_switching():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        if request.method == "GET":
            operatorSwitchingId = request.args.get("operatorSwitchingId","")
            operator_switching_queryset = OperatorSwitching.objects(id=operatorSwitchingId,status__in=[0,1]).first()
            if operator_switching_queryset:
                operator_switching_queryset.update(status=2)
                flash("Operator switching deleted successfully!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete operator switching!!")
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))

@switch_master.route("/update_operator_switching",methods=["POST","GET"])
def update_operator_switching():
    if not session.get("adminId"):
        return redirect("admin_login")
    try:
        operatorSwitchingId = request.args.get("operatorSwitchingId","")
        if request.method == "POST":
            userId = request.form.get("userId","")
            operatorId = request.form.get("operatorId","")
            apiCount = request.form.get("apiCount",0)
            apiId1 = request.form.get("apiId1","")
            apiId2 = request.form.get("apiId2","")
            apiId3 = request.form.get("apiId3","")
            apiId4 = request.form.get("apiId4","")
            apiId5 = request.form.get("apiId5","")
            apiId6 = request.form.get("apiId6","")
            apiId7 = request.form.get("apiId7","")

        if userId and operatorId and apiCount:
            try:
                operator_switching_queryset = OperatorSwitching.objects(id=operatorSwitchingId).first()
                if operator_switching_queryset:
                    operator_switching_queryset.update(
                        apiCount = apiCount,
                        userId = ObjectId(userId),
                        operatorId = ObjectId(operatorId),
                        apiId1 = ObjectId(apiId1)
                        )
                    if apiId2 == "":
                        operator_switching_queryset.update(apiId2 = None)
                    else:
                        operator_switching_queryset.update(apiId2 = ObjectId(apiId2))

                    if apiId3 == "":
                        operator_switching_queryset.update(apiId3 = None)
                    else:
                        operator_switching_queryset.update(apiId3 = ObjectId(apiId3))

                    if apiId4 == "":
                        operator_switching_queryset.update(apiId4 = None)
                    else:
                        operator_switching_queryset.update(apiId4 = ObjectId(apiId4))

                    if apiId5 == "":
                        operator_switching_queryset.update(apiId5 = None)
                    else:
                        operator_switching_queryset.update(apiId5 = ObjectId(apiId5))

                    if apiId6 == "":
                        operator_switching_queryset.update(apiId6 = None)
                    else:
                        operator_switching_queryset.update(apiId6 = ObjectId(apiId6))

                    if apiId7 == "":
                        operator_switching_queryset.update(apiId7 = None)
                    else:
                        operator_switching_queryset.update(apiId7 = ObjectId(apiId7))

                    flash("Operator switching updated successfully!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
            except Exception as e:
                app.logger.error(traceback.format_exc())
                flash("Unable to update operator switching!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
        else:
            flash("Required fields are missing!!")
            return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to update operator switching!!")
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Operatorswitching"))


############################## Amount Switching ##########################################
@switch_master.route("/add_amount_switching",methods=["POST","GET"])
def add_amount_switching():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        
        if request.method == "POST":
            userId = request.form.get("userId","")
            operatorId = request.form.get("operatorId","")
            amount = request.form.get("amount",0)
            transactionAPIId = request.form.get("transactionAPIId","")
            stateId = request.form.get("stateId","")

            if userId and operatorId and amount and transactionAPIId:
                try:
                    amount_switching_table = AmountSwitching(
                        adminId = adminId,
                        userId = userId,
                        operatorId = operatorId,
                        transactionAPIId = transactionAPIId,
                        amount = amount,
                        createdOn = datetime.datetime.now(),
                        status = 1,
                        )
                    save_table = amount_switching_table.save()
                    if stateId == "":
                        save_table.update(stateId = None)
                    else:
                        save_table.update(stateId = ObjectId(stateId))

                    flash("Amount switching saved successfully!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
                except Exception as e:
                    flash("Unable to save amount switching!!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to save amount switching!!"
        return render_template("super_admin_templates/switch_masters_list.html",error=error)

def fetching_amount_switching_details(amount_switching_queryset):
    amount_switching_dict = {}
    try:
        amount_switching_dict={
        "id":str(amount_switching_queryset.id),
        "userId":str(amount_switching_queryset.userId.id),
        "operatorId":str(amount_switching_queryset.operatorId.id),
        "transactionAPIId":str(amount_switching_queryset.transactionAPIId.id),
        "transactionAPIIdName":amount_switching_queryset.transactionAPIId.apiName,
        "operatorName":amount_switching_queryset.operatorId.operatorName,
        "userName":amount_switching_queryset.userId.fullName,
        "amount":amount_switching_queryset.amount
        }
        if amount_switching_queryset.stateId:
            amount_switching_dict["stateId"] = str(amount_switching_queryset.stateId.id)
            amount_switching_dict["stateName"] = amount_switching_queryset.stateId.stateName
        else:
            amount_switching_dict["stateId"] = ""
            amount_switching_dict["stateName"] = ""

        if amount_switching_queryset.status==1:
            amount_switching_dict["actionText"] = "Active"
        else:
            amount_switching_dict["actionText"] = "Deactive"
        if amount_switching_queryset.createdOn:
            amount_switching_dict["createdOn"] = amount_switching_queryset.createdOn.strftime("%m-%d-%Y")
        else:
            amount_switching_dict["createdOn"] = ""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return amount_switching_dict


@switch_master.route("/update_amount_switching_status",methods=["POST","GET"])
def update_amount_switching_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    amountSwitchingId = request.args.get("amountSwitchingId","")
    if amountSwitchingId:
        try:
            amount_switching_queryset = AmountSwitching.objects(id=amountSwitchingId, status__nin=[2]).first()
            if amount_switching_queryset:
                if amount_switching_queryset.status == 0:
                    amount_switching_queryset.update(status=1)
                    flash("Amount switching activated successfully!")
                elif amount_switching_queryset.status == 1:
                    amount_switching_queryset.update(status=0)
                    flash("Amount switching deactivated successfully!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
    else:
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))


@switch_master.route("/delete_amount_switching",methods=["GET"])
def delete_amount_switching():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        if request.method == "GET":
            amountSwitchingId = request.args.get("amountSwitchingId","")
            amount_switching_queryset = AmountSwitching.objects(id=amountSwitchingId,status__in=[0,1]).first()
            if amount_switching_queryset:
                amount_switching_queryset.update(status=2)
                flash("Amount switching deleted successfully!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete amount switching!!")
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))

@switch_master.route("/update_amount_switching",methods=["POST","GET"])
def update_amount_switching():
    if not session.get("adminId"):
        return redirect("admin_login")
    try:
        amountSwitchingId = request.args.get("amountSwitchingId","")
        if request.method == "POST":
            userId = request.form.get("userId","")
            operatorId = request.form.get("operatorId","")
            amount = request.form.get("amount",0)
            transactionAPIId = request.form.get("transactionAPIId","")
            stateId = request.form.get("stateId","")

        if userId and operatorId and amount and transactionAPIId:
            try:
                amount_switching_queryset = AmountSwitching.objects(id=amountSwitchingId).first()
                if amount_switching_queryset:
                    amount_switching_queryset.update(
                        amount = amount,
                        userId = ObjectId(userId),
                        operatorId = ObjectId(operatorId),
                        transactionAPIId = ObjectId(transactionAPIId)
                        )
                    if stateId == "":
                        amount_switching_queryset.update(stateId = None)
                    else:
                        amount_switching_queryset.update(stateId = ObjectId(stateId))

                    flash("Amount switching updated successfully!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
            except Exception as e:
                app.logger.error(traceback.format_exc())
                flash("Unable to update amount switching!!")
                return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
        else:
            flash("Required fields are missing!!")
            return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to update amount switching!!")
        return redirect(url_for("switch_master.switch_masters_list",redirectto="Amountswitching"))