from flask import Blueprint, render_template, redirect, url_for, session, request, flash
from definitions.models import db, User
from config import BrandingConfig

homepage_bp = Blueprint('homepage', __name__)

@homepage_bp.route('/')
def index():
    # Redirect to /viewall if the user is already logged in
    if 'username' in session:
        return redirect(url_for('viewall.view_list'))
    # Otherwise, redirect to the login page
    return redirect(url_for('homepage.login'))

@homepage_bp.route('/login/', methods=['GET', 'POST'])
def login():
    # Redirect to /viewall if the user is already logged in
    if 'username' in session:
        return redirect(url_for('viewall.view_list'))

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # Query the database for the user
        user = User.query.filter_by(username=username).first()

        # Validate credentials
        if user and user.check_password(password):
            session['username'] = username  # Store username in session
            return redirect(url_for('viewall.view_list'))
        else:
            flash('Invalid username or password', 'error')

    return render_template('login.html', brandingconfig=BrandingConfig)

@homepage_bp.route('/logout/')
def logout():
    # Remove the username from the session
    session.pop('username', None)
    return redirect(url_for('homepage.login'))