""" The admin controller to manage all of the admin related endpoints
    in the web app
"""

from flask import render_template, Blueprint, redirect, url_for, flash, request

from controllers.database.user import UserController
from controllers.database.product import ProductController

from utils.user_utils import is_role

# Blueprint to append user endpoints to
blueprint = Blueprint("admin", __name__, url_prefix="/admin")


@blueprint.before_request
def check_admin_user():
    """ Preprocess for all admin endpoints to ensure that the requesting
        user is logged in as an 'Admin'
    """
    if not is_role("Admin"):
        flash("You must be logged in as an Admin to view this page.", "error")
        return redirect(url_for('main.index'))


@blueprint.route('/')
def main():
    """ Function responsible for delivering the admin page for the site """
    return "Hello, World"


@blueprint.route('/users/')
def users():
    """ Endpoint responsible for managing a users permissions """
    # Get all users to create admin table on frontend
    db = UserController()

    search = request.args.get('search')

    # Don't try submitting a None Type
    if not search:
        search = ""

    users = db.read_all(search)

    return render_template("index.html", content="admin.html", users=users)


@blueprint.route('/products/')
def products():
    """ Endpoint responsible for managing products on the site """
    # Get all products to create admin table on frontend
    db = ProductController()

    search = request.args.get('search')

    # Don't try submitting a None Type
    if not search:
        search = ""

    products = db.read_all("", search)

    return render_template(
        "index.html",
        content="admin.html",
        products=products
    )
