""" The user controller to manage all of the user related endpoints
    in the web app
"""
from flask import Blueprint

from flask import render_template, redirect, request, session, flash
from controllers.database.user import UserController
from models.users.customer import Customer
from models.users.seller import Seller
from hashlib import sha512

# Blueprint to append user endpoints to
blueprint = Blueprint("users", __name__)


# LOGIN FUNCTIONALITY
@blueprint.route('/login')
def display_login():
    """ Function responsible for delivering the Login page for the site """
    return render_template('index.html', content="login.html")


@blueprint.post('/login')
def login():
    """ Function to handle the backend processing of a login request """
    database = UserController()
    user = database.read(request.form['username'])
    error = None

    # No user found
    if user is None:
        error = "No user found with the username " + request.form['username']
        flash(error, 'warning')
        return redirect("/login")

    # Incorrect Password
    if sha512(request.form['password'].encode()).hexdigest() != user.password:
        error = "Incorrect Password"
        flash(error, 'warning')
        return redirect("/login")

    session['user_id'] = user.id
    return redirect("/")


# SIGNUP FUNCTIONALITY
@blueprint.route('/signup')
def display_signup():
    """ Function responsible for delivering the Signup page for the site """
    return render_template('index.html', content="signup.html")


@blueprint.post('/signup')
def signup():
    """ Function to handle the backend processing of a signup request """
    database = UserController()

    # User already exists
    if database.read(request.form['username']) is not None:
        error = "User, " + request.form['username'] + " already exists"
        flash(error, 'warning')
        return redirect("/signup")

    # Signup as Seller or Customer
    if request.form.get('seller'):
        user = Seller(
            request.form['username'],
            # Hashed as soon as it is recieved on the backend
            sha512(request.form['password'].encode()).hexdigest(),
            request.form['firstname'],
            request.form['lastname'],
            request.form['email'],
            "123"
        )
    else:
        user = Customer(
            request.form['username'],
            # Hashed as soon as it is recieved on the backend
            sha512(request.form['password'].encode()).hexdigest(),
            request.form['firstname'],
            request.form['lastname'],
            request.form['email'],
            "123"
        )

    database.create(user)

    # Code 307 Preserves the original request (POST)
    return redirect("/login", code=307)


# SIGN OUT FUNCTIONALITY
@blueprint.route('/logout')
def logout():
    """ Function responsible for handling logouts from the site """
    # Clear the current user from the session if they are logged in
    session.pop('user_id', None)
    return redirect("/")
