from appservices.common.util import *
from flask import session
adminUser = Blueprint("adminUser",__name__)

@adminUser.route("/login", methods=["POST", "GET"])
def login():
    data_status = {"responseStatus": 0, "result": ""}
    email = request.form.get("email", "")
    password = request.form.get("password", "")
    
    if email and password:
        try:
            admin_queryset = GrievanceAdmin.objects(email__iexact=email).first()
            if admin_queryset:
                if check_password_hash(admin_queryset.password, password):
                    mobileNumber=str(admin_queryset.mobileNumber)
                    if admin_queryset.status == 1:
                        message=admin_queryset.name+" admin login successfully!"
                        
                        adminData=fetch_admin_details(admin_queryset)
                        first_chars = re.findall(r'\b\w', admin_queryset.name)
                        imageString = ''.join(first_chars)

                        session["GrievanceAdminId"] = str(admin_queryset.id)
                        session["name"] = admin_queryset.name
                        session["imageString"] = imageString
                       
                        return redirect(url_for("adminUser.dashboard"))
                    else:
                        error = "Inactive account!"
                        return render_template("grievance/admin/admin_login.html", error=error)
                else:
                    error = "Wrong password!"
                    return render_template("grievance/admin/admin_login.html", error=error)
            else:
                error = "Invalid email id!"
                return render_template("grievance/admin/admin_login.html", error=error)
        except Exception as e:
            app.logger.error(traceback.format_exc())
            return render_template("grievance/admin/admin_login.html")
    else:
        # error = "Required fields are missing!!"
        return render_template("grievance/admin/admin_login.html")


@adminUser.route("/dashboard",methods=["POST","GET"])
# @token_required
def dashboard():
    try:
        if not session.get("GrievanceAdminId"):
            return redirect("login")
        GrievanceAdminId = session.get("GrievanceAdminId")
        adminDict = {}
        admin_queryset = GrievanceAdmin.objects(id=GrievanceAdminId,status__in=[1]).first()
        grievancesCount = Grievances.objects().all()
        grievancesAllCount = grievancesCount.count()
        grievancesPendingCount = grievancesCount.filter(status=0).count()
        grievancesAcceptCount = grievancesCount.filter(status=1).count()
        grievancesRejectCount = grievancesCount.filter(status=2).count()
        grievancesDeparmentsUsersCount = GrievanceDepartmentUsers.objects(status=1).count()
        departmentsCount = Departments.objects(status=1).count()

        adminDict = {
        "name":admin_queryset.name,
        "grievancesCount":grievancesAllCount,
        "grievancesPendingCount":grievancesPendingCount,
        "grievancesAcceptCount":grievancesAcceptCount,
        "grievancesRejectCount":grievancesRejectCount,
        "grievancesDeparmentsUsersCount":grievancesDeparmentsUsersCount,
        "departmentsCount":departmentsCount
        }
        return render_template(
            "grievance/admin/dashboard.html",
             adminDict=adminDict,
            )
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('adminUser.login'))


@adminUser.route("/admin_profile_details",methods=["POST","GET"])
def admin_profile_details():
    try:
        if not session.get("GrievanceAdminId"):
            return redirect("login")

        GrievanceAdminId = session.get("GrievanceAdminId")
        
        admin_queryset = GrievanceAdmin.objects(id=GrievanceAdminId).first()

        if admin_queryset:
            adminDict = fetch_admin_details(admin_queryset)
            return render_template("grievance/admin/admin_profile_details.html",adminDict=adminDict)
        else:
            return redirect(url_for('adminUser.dashboard'))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return redirect(url_for('adminUser.dashboard'))


def fetch_admin_details(admin_queryset):
    loginDict={}
    try:
        loginDict={
        "id":str(admin_queryset.id),
        "name":admin_queryset.name,
        "email":admin_queryset.email,
        "mobileNumber":admin_queryset.mobileNumber,
        "createdOn":admin_queryset.createdOn.astimezone(tzinfo),
        "status":admin_queryset.status
        }
        
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return loginDict

@adminUser.route("/admin_change_password", methods=["POST", "GET"])
def admin_change_password():
    if not session.get("GrievanceAdminId"):
        return redirect(url_for("adminUser.login"))
    GrievanceAdminId = session.get("GrievanceAdminId")
    loginBrowser = request.headers.get("Sec-Ch-Ua")
    userAgent = request.headers.get("User-Agent")
    if loginBrowser:
        loginBrowseData = loginBrowser.split(";")
        browser = loginBrowseData[0]
    else:
        loginBrowseData = userAgent.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()
    existing_record = ""
    requestData = []
    
    if request.method == "GET":
        print("GET request received.")
        try:
            admin_queryset = GrievanceAdmin.objects(id=GrievanceAdminId).first()
            existing_record = admin_queryset.to_json()
            updatedrequestData = [existing_record]
            if not admin_queryset:
                flash("Invalid admin id!")
                return redirect(url_for("adminUser.login"))
            adminDict = fetch_admin_details(admin_queryset)
            return render_template("grievance/admin/admin_profile_details.html", adminDict=adminDict)
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Server Connection Error. Please try again!")
            return redirect(url_for("adminUser.login"))

    if request.method == "POST":
        print("POST request received.")
        oldPassword = request.form.get("oldPassword", "")
        newPassword = request.form.get("newPassword", "")
        confirmNewPassword = request.form.get("confirmNewPassword", "")

        print(f"Form Data: oldPassword={oldPassword}, newPassword={newPassword}, confirmNewPassword={confirmNewPassword}")

        if not oldPassword or not newPassword or not confirmNewPassword:
            flash("Required fields are missing!")
            return redirect(url_for("adminUser.admin_change_password"))

        try:
            admin_queryset = GrievanceAdmin.objects(id=GrievanceAdminId).first()
            if not admin_queryset:
                flash("Invalid admin id!")
                return redirect(url_for("adminUser.login"))

            print(f"Admin Query Result: {admin_queryset}")

            if check_password_hash(admin_queryset.password, oldPassword):
                print("Old password is correct.")
                if newPassword == confirmNewPassword:
                    admin_queryset.update(password=generate_password_hash(newPassword))
                    flash("Successfully changed the password!")
                    return redirect(url_for("adminUser.admin_change_password"))
                else:
                    flash("New password and confirm new password do not match!")
                    return redirect(url_for("adminUser.admin_change_password"))
            else:
                flash("Old password is incorrect!")
                return redirect(url_for("adminUser.admin_change_password"))
        except Exception as e:
            app.logger.error(traceback.format_exc())
            flash("Server Connection Error. Please try again!")
            return redirect(url_for("adminUser.login"))