import functools
from datetime import datetime, timezone

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify
)
from werkzeug.security import check_password_hash, generate_password_hash

from wurker.ui.db import get_db

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


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

        db = get_db()
        error = None
        user = db.execute(
            'SELECT * FROM user WHERE username = ?', (username,)
        ).fetchone()

        if user is None:
            error = 'Incorrect username or password'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password or password'

        if error is None:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    result = {"thisYear": datetime.now(timezone.utc).strftime('%Y')}
    return render_template('auth/login.html', **result)


@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 = get_db().execute(
            'SELECT * FROM user WHERE id = ?', (user_id,)
        ).fetchone()


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


def login_required(view):
    """Decorator to require Wurker UI Auth."""

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

        return view(*args, **kwargs)

    return wrapped_view


def api_auth_required(endpoint):
    """Decorator to require Wurker API Auth."""

    @functools.wraps(endpoint)
    def wrapped_endpoint(*args, **kwargs):
        auth = request.authorization
        error = check_api_auth(auth)
        if error:
            return jsonify({'message': 'Authentication required', 'error': error}), 401

        return endpoint(*args, **kwargs)

    return wrapped_endpoint


def check_api_auth(auth):
    """Validate auth if applicable for this instance."""

    # TODO 1st check if this API is public (no auth)
    db = get_db()
    api_users = db.execute('SELECT * FROM api_auth').fetchall()
    if not len(api_users):
        return

    # TODO Not public? Then Basic HTTP Auth, for now
    if not auth or not auth["username"] or not auth["password"]:
        return 'Username or password not set'

    api_user = db.execute(
        'SELECT * FROM api_auth WHERE username = ?', (auth.username,)
    ).fetchone()

    if api_user is None:
        return 'Username or password not found'

    if not check_password_hash(api_user['password'], auth.password):
        return 'Username or password does not match'
