import functools
import imp

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from hashlib import md5
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from create_db import User
from config import CONFIG 


bp = Blueprint('auth', __name__, url_prefix='/auth')

engine = create_engine(CONFIG['DB_CONNECTION'])
dbsessionmaker = sessionmaker(bind=engine)
dbsession = dbsessionmaker()

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'

        if error is None:
            try:
                user = User(username=username, password=md5(password.encode("utf-8")).hexdigest())
                dbsession.add(user)
                dbsession.commit()


            except Exception as e:
                error = f"napaka pri registraciji {username} je {e}"
            else:
                return redirect(url_for("auth.login"))

        flash(error)

    return render_template('auth/register.html')


@bp.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        error = None
        user = dbsession.query(User).filter(User.username == username).first()
        
        if user is None:
            error = 'Incorrect username.'
        elif not user.password == md5(password.encode("utf-8")).hexdigest(): #compare input pw has and bd pw hash

            error = 'Incorrect password.'

        if error is None:
            session.clear()
            session['user_id'] = user.id
            session['username'] = user.username
            return redirect(url_for("menu.index")) #TODO ne dela
        flash(error)

    return render_template('auth/login.html')


@bp.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = None


@bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view