from flask import render_template, abort, redirect, url_for, abort, flash, request, current_app, make_response, g
from flask_login import fresh_login_required, login_user, logout_user
#from flask_sqlalchemy import get_recorded_queries

from . import admin

from mailsender import send_email
from models import db, User, Item
from decorators import admin_required, permission_required

import base64
import string
import random
from datetime import datetime, timedelta, date, time

#@admin.after_app_request
#def after_request(response):
#    for query in get_recorded_queries():
#        if query.duration >= current_app.config['SLOW_DB_QUERY_TIME']:
#            current_app.logger.warning('Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n' % (query.statement, query.parameters, query.duration, query.context))
#    return response

@admin.route("/", methods=['GET'])
@fresh_login_required
@admin_required
def index():
    return redirect(url_for('admin.list_users'))

@admin.route("/listusers/", defaults={'page': 1})
@admin.route("/listusers/<int:page>", methods=['GET'])
@fresh_login_required
@admin_required
def list_users(page):
    sqlquery = User.query.filter_by(active=True).order_by(User.last_seen.desc()).paginate(page=page, per_page=int(current_app.config['ITEMS_PER_PAGE']), error_out=False)
    return render_template('admin/list_users.html', users=sqlquery.items, page=page)

@admin.route("/listitems", methods=['GET'])
@fresh_login_required
@admin_required
def list_items():
    allservices = Item.query.order_by(Item.date_created.asc()).all()
    return render_template('admin/list_items.html', items=allitems)
