from appservices.common.util import *

wallet_master = Blueprint("wallet_master",__name__)

# Add Settlement
@wallet_master.route("/add_wallet",methods=["POST","GET"])
def add_wallet():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        
        if request.method == "POST":
            walletName = request.form.get("walletName","")
            code = request.form.get("code","")
            description = request.form.get("description","")
            if walletName and code:
                try:
                    wallet_table = Wallet(
                        adminId = adminId,
                        walletName = walletName,
                        code = code,
                        description = description,
                        createdOn = datetime.datetime.now(),
                        status = 1,
                        )
                    save_table = wallet_table.save()
                    walletId = str(save_table.id)
                    flash("Wallet saved successfully!")
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
                except Exception as e:
                    flash("Unable to save wallet!!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to save wallet!!"
        return render_template("super_admin_templates/wallet_masters_list.html",error=error)


# View All wallet list
@wallet_master.route("/wallets_list",methods=["POST","GET"])
def wallets_list():
    if not session.get("adminId"):
        return redirect("admin_login")
    adminId = session.get("adminId")
    walletsList = []
    sourceOfFundsList = []
    categoriesList =[]
    try:
        redirectTo = request.args.get("redirectTo","Wallet")
        if redirectTo:
            redirectval = redirectTo
        else:
            redirectval = "Wallet"
        search = False


        ############# wallet data ############

        wallet_search_element = request.args.get('wallet_search_element','')
        if wallet_search_element:
        # if not wallet_search_element:
        #     wallet_search_element = request.form.get("wallet_search_element","")
        # if wallet_search_element:
            search = True

        # page = request.args.get(get_page_parameter(), type=int, default=1)
        # page_start,page_end=fetch_limit_length_based_on_page_index(page,20)
        # pagination = Pagination(
        #     page=page,
        #     record_name='wallets',
        #     per_page=20,
        #     alignment="right"
        #     )

        page = request.args.get(get_page_parameter(), type=int, default=1)
        page_start,page_end=fetch_limit_length_based_on_page_index(page,1)
        per_page = 1

        # pagination = Pagination(page=page, total=total_records, per_page=per_page)

        wallets_queryset = Wallet.objects(adminId=adminId,status__in=[0,1]).order_by("-id")
        if wallet_search_element:
            wallets_queryset = wallets_queryset.filter(Q(walletName__icontains=wallet_search_element))
        total_records = wallets_queryset.count()
        print("{{{{{{{{{{{{{{page}}}}}}}}}}}}}}",page)
        print("{{{{{{{{{{{{{{total_records}}}}}}}}}}}}}}",total_records)
        print("{{{{{{{{{{{{{{page_start}}}}}}}}}}}}}}",page_start)
        print("{{{{{{{{{{{{{{page_end}}}}}}}}}}}}}}",page_end)
        wallets_queryset=wallets_queryset[page_start:page_end]
        for each_wallet in wallets_queryset:
            wallet_dict = fetching_wallets_details(each_wallet)
            walletsList.append(wallet_dict)

        pagination = Pagination(page=page,total=total_records, per_page=per_page)


        ############# source of fund data ############

        source_of_fund_search_element = request.args.get('source_of_fund_search_element','')
        if source_of_fund_search_element:
            search = True
            # page = request.args.get(get_page_parameter(), type=int, default=1)
            # page_start,page_end=fetch_limit_length_based_on_page_index(page,20)
            # pagination = Pagination(
            #     page=page,
            #     record_name='wallets',
            #     per_page=20,
            #     alignment="right"
            #     )

        source_of_funds_queryset = SourceOfFunds.objects(adminId=adminId,status__in=[0,1]).order_by("-id")

        if source_of_fund_search_element:
            source_of_funds_queryset = source_of_funds_queryset.filter(Q(sourceName__icontains=source_of_fund_search_element))
        #total_records = source_of_funds_queryset.count()
        # source_of_funds_queryset=source_of_funds_queryset[page_start:page_end]
        for each_source_of_fund in source_of_funds_queryset:
            source_of_fund_dict = fetching_source_of_fund_details(each_source_of_fund)
            sourceOfFundsList.append(source_of_fund_dict)


       

        ############# category list ############
        categories_queryset = Categories.objects(adminId=adminId,status__in=[0,1]).order_by("-id")
        for each_categry in categories_queryset:
            category_dict = {
            "id":str(each_categry.id),
            "categoryName":each_categry.categoryName,
            }
            categoriesList.append(category_dict)

        return render_template("super_admin_templates/wallet_masters_list.html", 
            walletsList=walletsList,
            sourceOfFundsList=sourceOfFundsList,
            categoriesList=categoriesList,
            wallet_search_element=wallet_search_element,
            source_of_fund_search_element=source_of_fund_search_element,
            pagination=pagination,
            redirectval = redirectval
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        error = "Unable to fetch wallets details!!"
        return render_template("super_admin_templates/wallet_masters_list.html",
            walletsList=walletsList,
            sourceOfFundsList=sourceOfFundsList,
            categoriesList=categoriesList,
            wallet_search_element=wallet_search_element,
            # source_of_fund_search_element=source_of_fund_search_element,
            # pagination=pagination,
            redirectval = redirectval,
            error = error
            )

# Update wallet status
@wallet_master.route("/update_wallet_status",methods=["POST","GET"])
def update_wallet_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    walletId = request.args.get("walletId","")
    if walletId:
        try:
            wallet_queryset = Wallet.objects(id=walletId,status__nin=[2]).first()
            if wallet_queryset:
                if wallet_queryset.status == 0:
                    wallet_queryset.update(status=1)
                    flash("Wallet activated successfully!")
                elif wallet_queryset.status == 1:
                    wallet_queryset.update(status=0)
                    flash("Wallet deactivated successfully!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
    else:
        return redirect(url_for("wallet_master.wallets_list"))


# Delete wallet 
@wallet_master.route("/delete_wallet",methods=["GET"])
def delete_wallet():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        if request.method == "GET":
            walletId = request.args.get("walletId","")
            wallet_queryset = Wallet.objects(id=walletId,status__in=[0,1]).first()
            if wallet_queryset:
                wallet_queryset.update(status=2)
                flash("Wallet deleted successfully!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete wallet!!")
        return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))


# Update wallet
@wallet_master.route("/update_wallet",methods=["POST","GET"])
def update_wallet():
    if not session.get("adminId"):
        return redirect("admin_login")
    try:
        walletId = request.args.get("walletId","")
        if request.method == "POST":
            walletName = request.form.get("walletName","")
            code = request.form.get("code","")
            description = request.form.get("description","")

            if walletName and code:
                try:
                    wallet_queryset = Wallet.objects(id=walletId).first()
                    if wallet_queryset:
                        wallet_queryset.update(
                            walletName = walletName,
                            code = code,
                            description = description,
                            )
                        flash("Wallet updated successfully!")
                        return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
                    else:
                        flash("Invaild id!!")
                        return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
                except Exception as e:
                    app.logger.error(traceback.format_exc())
                    flash("Unable to update wallet!!")
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to update wallet!!")
        return redirect(url_for("wallet_master.wallets_list",redirectTo="Wallet"))


################################### SOURCE OF FUND ###################################
# Add source of fund
@wallet_master.route("/add_source_of_fund",methods=["POST","GET"])
def add_source_of_fund():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        adminId = session.get("adminId")
        
        if request.method == "POST":
            sourceName = request.form.get("sourceName","")
            categoryId = request.form.get("categoryId","A")
            code = request.form.get("code","")
            description = request.form.get("description","")
            rank = request.form.get("rank",0)
            print(request.form,"?????????????????????")
            print(categoryId,"((((((((((((categoryId))))))))))))")
            if sourceName and categoryId and code and rank:
                try:
                    source_table = SourceOfFunds(
                        adminId = adminId,
                        sourceName = sourceName,
                        categoryId = categoryId,
                        code = code,
                        description = description,
                        rank = rank,
                        createdOn = datetime.datetime.now(),
                        status = 1,
                        )
                    save_table = source_table.save()
                    sourceOfFundId = str(save_table.id)
                    flash("Source of fund saved successfully!")
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
                except Exception as e:
                    flash("Unable to save source of fund!!")
                    app.logger.error(traceback.format_exc())
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to save source of fund!!")
        return render_template("super_admin_templates/wallets_list.html",error=error)



def fetching_source_of_fund_details(source_of_fund_queryset):
    source_of_fund_dict = {}
    try:
        source_of_fund_dict={
        "id":str(source_of_fund_queryset.id),
        "sourceName":source_of_fund_queryset.sourceName,
        "code":source_of_fund_queryset.code,
        "rank":source_of_fund_queryset.rank,
        "description":source_of_fund_queryset.description,
        }
        try:
            if source_of_fund_queryset.categoryId:
                source_of_fund_dict["categoryId"]=str(source_of_fund_queryset.categoryId.id)
                source_of_fund_dict["categoryName"]=source_of_fund_queryset.categoryId.categoryName
            else:
                source_of_fund_dict["categoryId"]=""
                source_of_fund_dict["categoryName"]=""
        except Exception as e:
            source_of_fund_dict["categoryId"]=""
            source_of_fund_dict["categoryName"]=""
        if source_of_fund_queryset.status==1:
            source_of_fund_dict["actionText"] = "Active"
        else:
            source_of_fund_dict["actionText"] = "Deactive"
        if source_of_fund_queryset.createdOn:
            source_of_fund_dict["createdOn"] = source_of_fund_queryset.createdOn.strftime("%m-%d-%Y")
        else:
            source_of_fund_dict["createdOn"] = ""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return source_of_fund_dict


# Update source of fund status
@wallet_master.route("/update_source_of_fund_status",methods=["POST","GET"])
def update_source_of_fund_status():
    if not session.get("adminId"):
        return redirect("admin_login")
    sourceOfFundId = request.args.get("sourceOfFundId","")
    if sourceOfFundId:
        try:
            source_of_fund_queryset = SourceOfFunds.objects(id=sourceOfFundId,status__nin=[2]).first()
            if source_of_fund_queryset:
                if source_of_fund_queryset.status == 0:
                    source_of_fund_queryset.update(status=1)
                    flash("Source of fund activated successfully!")
                elif source_of_fund_queryset.status == 1:
                    source_of_fund_queryset.update(status=0)
                    flash("Source of fund deactivated successfully!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))

        except Exception as e:
            app.logger.error(traceback.format_exc())
            return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
    else:
        return redirect(url_for("wallet_master.wallets_list"))


# Delete source of fund 
@wallet_master.route("/delete_source_of_fund",methods=["GET"])
def delete_source_of_fund():
    try:
        if not session.get("adminId"):
            return redirect("admin_login")
        if request.method == "GET":
            sourceOfFundId = request.args.get("sourceOfFundId","")
            source_of_fund_queryset = SourceOfFunds.objects(id=sourceOfFundId,status__in=[0,1]).first()
            if source_of_fund_queryset:
                source_of_fund_queryset.update(status=2)
                flash("Source of fund deleted successfully!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
            else:
                flash("Invaild id!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete source of fund!!")
        return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))


# Edit source of fund 
@wallet_master.route("/update_source_of_fund",methods=["GET","POST"])
def update_source_of_fund():
    if not session.get("adminId"):
        return redirect("admin_login")
    try:
        sourceOfFundId = request.args.get("sourceOfFundId","")
        if request.method == "POST":
            sourceName = request.form.get("sourceName","")
            categoryId = request.form.get("categoryId","")
            code = request.form.get("code","")
            description = request.form.get("description","")
            rank = request.form.get("rank","")
            if sourceName and categoryId and code and rank:
                try:
                    source_of_fund_queryset = SourceOfFunds.objects(id=sourceOfFundId).first()
                    if source_of_fund_queryset:
                        source_of_fund_queryset.update(
                            sourceName = sourceName,
                            categoryId = ObjectId(categoryId),
                            code = code,
                            description = description,
                            rank = rank,
                            )
                        flash("Source of fund updated successfully!")
                        return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
                    else:
                        flash("Invaild id!!")
                        return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
                except Exception as e:
                    app.logger.error(traceback.format_exc())
                    flash("Unable to update source of fund!!")
                    return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
            else:
                flash("Required fields are missing!!")
                return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to update source of fund!!")
        return redirect(url_for("wallet_master.wallets_list",redirectTo="SourceOfFund"))
