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

from . import panel

from mailsender import send_email
from models import db, User, Permission, Item

import base64
from datetime import date, time, datetime

#@panel.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

#@panel.route("/deploy", methods=['GET', 'POST'])
#@login_required
#def deploy():
#    if current_user.name is None:
#        return redirect(url_for('settings.profile'))
#
#    form = OrderForm()
#    if form.validate_on_submit():
#        region = Region.query.filter_by(id=int(form.region.data)).first()
#        recipe = Recipe.query.filter_by(id=int(form.recipe.data)).first()
#        new_order = Order(user_id=int(current_user.id), region_id=int(region.id), recipe_id=int(recipe.id), parameter1=str(form.alias.data), parameter2=str(form.cpu.data), parameter3=str(form.memory.data), parameter4=str(form.storage.data), status='new')
#        db.session.add(new_order)
#        db.session.commit()
#        send_email(current_app.config['MAIL_USERNAME'], 'New order from {}'.format(current_user.email), 
#                                      'panel/email/adm_neworder', user=current_user)
#        return redirect(request.args.get('next') or url_for('panel.dashboard'))
#
#    return render_template('panel/deploy.html', form=form)

#DASHBOARD
@panel.route("/dashboard", defaults={'user_id': 0}, methods=['GET'])
@panel.route("/dashboard/<int:user_id>", methods=['GET'])
@login_required
def dashboard(user_id):
    if user_id == 0:
        cuser = current_user
    else:
        cuser = User.query.filter_by(id=user_id).first()
        if cuser == None:
            abort(404)
        if not current_user.is_administrator():
            abort(403)
                
    inv_items = cuser.inv_items.order_by(Item.date_created.asc()).all()

    return render_template('panel/dashboard.html', inv_items=inv_items)
