from appservices.common.util import *

tax_master = Blueprint("tax_master",__name__)

# Add Tax Type
@tax_master.route("/add_tax_type",methods=["POST","GET"])
def add_tax_type():
    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()
        permissionsList = check_permissions(adminId,"taxmasterPermissions")
        if "add" in permissionsList:
            if request.method == "POST":
                taxTypeName = request.form.get("taxTypeName","")
                taxType = request.form.get("taxType","")
                primaryTax = request.form.get("primaryTax","")
                secondaryTax = request.form.get("secondaryTax","")
                jsonData = request.form.to_dict(flat=True)
                requestData = [jsonData]
                updatedrequestData = [jsonData]
                if taxTypeName and taxType and primaryTax and secondaryTax:
                    try:
                        admin_queryset = SuperAdmin.objects(id=adminId,status=1).first()
                        if admin_queryset:
                            message=admin_queryset.userName+" "+taxTypeName+" Tax Type created successfully!"
                            save_admin_log_table = save_admin_logs_data(adminId,None,None,"add_tax_type","create",actionDate,client_ip,browser,message,requestData,updatedrequestData) 
                        taxType_table = TaxTypes(
                            adminId = adminId,
                            taxTypeName = taxTypeName,
                            taxType = taxType,
                            primaryTax = primaryTax,
                            secondaryTax = secondaryTax,
                            createdOn = datetime.datetime.now(),
                            status = 1,
                            )
                        save_table = taxType_table.save()
                        taxTypeId = str(save_table.id)
                        flash("Tax Type saved successfully!")
                        return redirect(url_for("tax_master.tax_types_list"))
                    except Exception as e:
                        flash("Unable to save tax type!!")
                        app.logger.error(traceback.format_exc())
                        return redirect(url_for("tax_master.tax_types_list"))
                else:
                    flash("Required fields are missing!!")
                    return redirect(url_for("tax_master.tax_types_list"))
        else:
            flash("Staff member does not have given create tax type permissions!!")
            return redirect(url_for("tax_master.tax_types_list"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        # flash("Unable to save tax type!!")
        error = "Unable to save tax type!!"
        return redirect(url_for("tax_master.tax_types_list",error=error))

def fetching_tax_type_details(taxType_queryset):
    taxType_dict = {}
    try:
        taxType_dict={
        "id":str(taxType_queryset.id),
        "taxTypeName":taxType_queryset.taxTypeName,
        "taxType":taxType_queryset.taxType,
        "primaryTax":taxType_queryset.primaryTax,
        "secondaryTax":taxType_queryset.secondaryTax,
        }
        if taxType_queryset.status==1:
            taxType_dict["actionText"] = "Active"
        else:
            taxType_dict["actionText"] = "Deactive"
        if taxType_queryset.createdOn:
            taxType_dict["createdOn"] = taxType_queryset.createdOn.strftime("%m-%d-%Y")
        else:
            taxType_dict["createdOn"] = ""
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return taxType_dict

# View All Tax Types
@tax_master.route("/tax_types_list",methods=["POST","GET"])
def tax_types_list():
    if not session.get("adminId"):
        return redirect("admin_login")
    taxTypesList = []
    adminId = session.get("adminId")
    # categories_queryset = Category.objects(status__in=[1]).order_by('-id').all()
    permissionsList = check_permissions(session.get("adminId"),"taxmasterPermissions")
    print(permissionsList,"((((((((permissionsList))))))))")
    if "view" in permissionsList:
        try:
            search = False  
            search_element = request.args.get('search_element','')
            if not search_element:
                search_element = request.form.get("search_element","")
            if 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='tax_master',
                per_page=20,
                alignment="right"
                )
            tax_type_queryset = TaxTypes.objects(status__in=[0,1]).order_by("-id")
            if search_element:
                tax_type_queryset = tax_type_queryset.filter(Q(taxTypeName__icontains=search_element))
                length = tax_type_queryset.count()
                tax_type_queryset=tax_type_queryset[page_start:page_end]
            else:
                length = tax_type_queryset.count()
                tax_type_queryset=tax_type_queryset[page_start:page_end]
            for each_tax_type in tax_type_queryset:
                taxType_dict = fetching_tax_type_details(each_tax_type)
                taxTypesList.append(taxType_dict)
            pagination = Pagination(
                page=page,
                total=length,
                found=length,
                record_name='tax_master',
                per_page=20,
                alignment="right"
                )
            return render_template("super_admin_templates/tax_master_list.html",
                taxTypesList=taxTypesList,
                search_element=search_element,
                pagination=pagination,
                )
        except Exception as e:
            app.logger.error(traceback.format_exc())
            error = "Unable to fetch tax type details!!"
            return render_template("super_admin_templates/tax_master_list.html",
                taxTypesList=taxTypesList,
                search_element=search_element,
                pagination=pagination,
                )
    else:
        flash("Staff member does not have given view tax master permissions!!")
        return redirect(url_for("admin.dashboard"))

# Update Tax Type
@tax_master.route("/update_tax_type",methods=["POST","GET"])
def update_tax_type():
    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]
    existing_record = ""
    client_ip=0
    # Extracting client IP address
    if request.headers.getlist("X-Forwarded-For"): 
        client_ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        client_ip = request.remote_addr

    actionDate=datetime.datetime.now()
    permissionsList = check_permissions(session.get("adminId"),"taxmasterPermissions")
    if "edit" in permissionsList:
        try:
            taxTypeId = request.args.get("taxTypeId","")
            if request.method == "POST":
                taxTypeName = request.form.get("taxTypeName","")
                taxType = request.form.get("taxType","")
                primaryTax = request.form.get("primaryTax","")
                secondaryTax = request.form.get("secondaryTax","")
                jsonData = request.form.to_dict(flat=True)

                if taxTypeName and taxType and primaryTax and secondaryTax:
                    try:
                        taxType_queryset = TaxTypes.objects(id=taxTypeId).first()
                        existing_record = taxType_queryset.to_json()
                        message=taxType_queryset.adminId.userName+" "+taxTypeName+" Tax Type updated successfully!"
                        requestData=[existing_record]
                        updatedrequestData=[jsonData]
                        save_admin_log_table = save_admin_logs_data(adminId,None,None,"update_tax_type","update",actionDate,client_ip,browser,message,requestData,updatedrequestData) 

                        if taxType_queryset:
                            taxType_queryset.update(
                                taxTypeName = taxTypeName,
                                taxType = taxType,
                                primaryTax = primaryTax,
                                secondaryTax = secondaryTax,
                                )
                            flash("Tax Type updated successfully!")
                            return redirect(url_for("tax_master.tax_types_list"))
                        else:
                            flash("Invaild id!!")
                            return redirect(url_for("tax_master.tax_types_list"))
                    except Exception as e:
                        app.logger.error(traceback.format_exc())
                        flash("Unable to update tax type!!")
                        return redirect(url_for("tax_master.tax_types_list"))
                else:
                    flash("Required fields are missing!!")
                    return redirect(url_for("tax_master.tax_types_list"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Unable to update tax type!!")
            return redirect(url_for("tax_master.tax_types_list"))
    else:
        flash("Staff member does not have given update tax type permissions!!")
        return redirect(url_for("tax_master.tax_types_list"))

# Update Tax Type Status
@tax_master.route("/update_tax_type_status",methods=["POST","GET"])
def update_tax_type_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"),"taxmasterPermissions")
    if "edit" in permissionsList:
        taxTypeId = request.args.get("taxTypeId","")
        if taxTypeId:
            try:
                taxType_queryset = TaxTypes.objects(id=taxTypeId,status__nin=[2]).first()
                existing_record = taxType_queryset.to_json()
                requestData = [existing_record]
                if taxType_queryset:
                    if taxType_queryset.status == 0:
                        taxType_queryset.update(status=1)
                        flash("Tax Type activated successfully!")
                        message=taxType_queryset.adminId.userName+" "+taxType_queryset.taxTypeName+" Tax Type activated successfully!"
                    elif taxType_queryset.status == 1:
                        taxType_queryset.update(status=0)
                        flash("Tax Type deactivated successfully!")
                        message=taxType_queryset.adminId.userName+" "+taxType_queryset.taxTypeName+" Tax Type deactivated successfully!"
                    save_admin_log_table = save_admin_logs_data(adminId,None,None,"update_tax_type_status","updatestatus",actionDate,client_ip,browser,message,requestData,updatedrequestData)
                    return redirect(url_for("tax_master.tax_types_list"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("tax_master.tax_types_list"))
            except Exception as e:
                app.logger.error(traceback.format_exc())
                return redirect(url_for("tax_master.tax_types_list"))
        else:
            return redirect(url_for("tax_master.tax_types_list"))
    else:
        flash("Staff member does not have given update status tax type permissions!!")
        return redirect(url_for("tax_master.tax_types_list"))

# Delete Tax Type
@tax_master.route("/delete_tax_type",methods=["GET"])
def delete_tax_type():
    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()

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

        existing_record = ""
        updatedrequestData = [jsonData]
        permissionsList = check_permissions(session.get("adminId"),"taxmasterPermissions")
        if "delete" in permissionsList:
            if request.method == "GET":
                taxTypeId = request.args.get("taxTypeId","")
                taxType_queryset = TaxTypes.objects(id=taxTypeId,status__in=[0,1]).first()
                existing_record = taxType_queryset.to_json()
                requestData = [existing_record]
                if taxType_queryset:
                    taxType_queryset.update(status=2)
                    flash("Tax Type deleted successfully!")
                    message=taxType_queryset.adminId.userName+" "+taxType_queryset.taxTypeName+" Tax Type deleted successfully!"
                    save_admin_log_table = save_admin_logs_data(adminId,None,None,"delete_tax_type","delete",actionDate,client_ip,browser,message,requestData,updatedrequestData)
                    return redirect(url_for("tax_master.tax_types_list"))
                else:
                    flash("Invaild id!!")
                    return redirect(url_for("tax_master.tax_types_list"))
        else:
            flash("Staff member does not have given delete tax type permissions!!")
            return redirect(url_for("tax_master.tax_types_list"))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        flash("Unable to delete tax type!!")
        return redirect(url_for("tax_master.tax_types_list"))