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_debug_queries

from . import dmanager
from .forms import ActivateForm
from .. import db
from ..email import send_email
from ..models import User, Permission, Service
from ..decorators import admin_required, permission_required

from datetime import datetime, timedelta, date, time

@dmanager.after_app_request
def after_request(response):
    for query in get_debug_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

@dmanager.route('/createdomain', methods=['GET', 'POST'])
@login_required
def createdomain():
    return(404)

@dmanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required
def activate(itemid=0):
    if current_user.wallet < 1:
        flash('Insufficient Funds')
        return redirect(url_for('uinvoice.transactions'))

    #work with disabled deploys only
    result = current_user.inv_domains.all()
    inventory = []
    for invcls in result:
        inventory.extend([invcls.pid])

    if current_user.is_administrator():
        current_app.logger.warning('[ADMIN] Access override for domain id:{}'.format(itemid))
    elif not itemid in inventory:
        current_app.logger.error('[{}] Access violation with domain id: {}'.format(current_user.email, itemid))
        abort(404)

    #current_app.logger.info('[{}] Disabled deployments: {}'.format(current_user.email, inventory))
    form = ActivateForm(period=Domain.query.filter_by(pid=itemid))
    if current_user.confirmed and form.validate_on_submit():
        current_app.logger.info('payment')
    return render_template('dmanager/activate.html', form=form, itemid=itemid)

