import datetime as dt
import logging

from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask import Markup
from flask_login import fresh_login_required, login_user, logout_user, current_user

from authmgr.extensions import login_manager
from authmgr.utils import flash_errors
from authmgr.extensions import db

from authmgr.user_directory.forms import UserDirectoryForm
from authmgr.user_directory.models import UserDirectory

blueprint = Blueprint('user_directory', __name__, url_prefix='/user_directory', static_folder='../static')

#User Directory views
@blueprint.route('/')
@fresh_login_required
def list():
    """
    List all User Directories
    """
    user_directories = UserDirectory.query.order_by('name').all()
    return render_template('user_directory/user_directories.html', user_directories=user_directories, title='User Directories')

@blueprint.route('/add', methods=['GET', 'POST'])
@fresh_login_required
def add():
    """
    Add a User Directory
    """
    add_user_directory = True

    form = UserDirectoryForm()
    if form.validate_on_submit():
        user_directory = UserDirectory(
                                directory_type=form.directory_type.data,
                                name=form.name.data,
                                description=form.description.data,
                                hostname=form.hostname.data,
                                port=form.port.data,
                                use_ssl=form.use_ssl.data,
                                basedn=form.basedn.data,
                                username=form.username.data,
                                password=form.password.data,
                                user_id=current_user.username,
                                updated_at=dt.datetime.utcnow()
                            )
        try:
            # add user_directory to the database
            db.session.add(user_directory)
            db.session.commit()
            flash('User Directory added.', 'success')
        except:
            #logger.error(str(traceback.print_exc()))
            # in case User Directory name already exists
            flash('Error: User Directory already exists.', 'warning')

        # redirect to the User Directory list page
        return redirect(url_for('user_directory.list'))

    # load setting template
    return render_template('user_directory/user_directory.html', add_user_directory=add_user_directory, form=form, title='Add User Directory')


@blueprint.route('/edit/<int:id>', methods=['GET', 'POST'])
@fresh_login_required
def edit(id):
    """
    Edit a User Directory
    """
    add_user_directory = False

    user_directory = UserDirectory.query.get_or_404(id)
    form = UserDirectoryForm(obj=user_directory)
    if form.validate_on_submit():
        user_directory.directory_type=form.directory_type.data,
        user_directory.name=form.name.data,
        user_directory.description=form.description.data,
        user_directory.hostname=form.hostname.data,
        user_directory.port=form.port.data,
        user_directory.use_ssl=form.use_ssl.data,
        user_directory.basedn=form.basedn.data,
        user_directory.username=form.username.data,
        user_directory.password=form.password.data
        user_directory.user_id=current_user.username
        user_directory.updated_at=dt.datetime.utcnow()
        db.session.commit()
        flash('User Directory updated.', 'success')
        # redirect to the user_directories page
        return redirect(url_for('user_directory.list'))

    return render_template('/user_directory.html', add_user_directory=add_user_directory, form=form, title='Edit User Directory')


@blueprint.route('/user_directories/delete/<int:id>', methods=['GET', 'POST'])
@fresh_login_required
def delete(id):
    """
    Delete a User Directory from the database
    """

    user_directory = UserDirectory.query.get_or_404(id)
    db.session.delete(user_directory)
    db.session.commit()
    flash('User Directory deleted.', 'success')

    # redirect to the roles page
    return redirect(url_for('user_directory.list'))
