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 smanager
from .forms import ActivateForm
from .. import db
from ..email import send_email
from ..models import User, Permission, Service, Transaction
from ..decorators import admin_required, permission_required

from datetime import datetime, timedelta, date, time
from dateutil.relativedelta import relativedelta

@smanager.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

@smanager.route('/requestservice', methods=['GET', 'POST'])
@login_required
def requestservice():
    abort(403)

@smanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required
def activate(itemid=0):
    result = current_user.inv_services.all()
    inventory = []
    for invcls in result:
        inventory.extend([invcls.pid])
    if current_user.is_administrator():
        current_app.logger.warning('[ADMIN] Access override for service id:{}'.format(itemid))
    elif not itemid in inventory:
        current_app.logger.error('[{}] Access violation with service id: {}'.format(current_user.email, itemid))
        abort(404)

    service = Service.query.filter_by(pid=itemid).first()
    if service.enabled == True and service.warning == False:
        abort(404)
    ppm = float(service.price)
    form = ActivateForm(period=int(service.period))

    owner = service.owner
    if owner.confirmed and form.validate_on_submit():
        total = ppm * form.period.data
        if owner.wallet < total:
            flash('Activation costs {} {}. Insufficient Funds'.format(total, owner.currency))
            return redirect(url_for('uinvoice.transactions'))
        current_app.logger.info('[{}] Charge service: {}'.format(owner.email, service.description))
        today = datetime.utcnow()
        expiry = today + relativedelta(today, months=+(form.period.data))
        daysleft = expiry - today
        extradays = relativedelta(today, days=+(service.daysleft))
        service.date_last_charge = today + extradays
        service.period = form.period.data
        service.daysleft = daysleft.days + extradays.days 
        service.warning = False
        service.enabled = True
        db.session.commit()

        transaction = Transaction(user_id=int(owner.pid), description='Deployment {} activated for {} month(s)'.format(str(service.description), form.period.data), value=-total)
        db.session.add(transaction)
        db.session.commit()

        owner.wallet = owner.wallet - total
        db.session.commit()

        if owner.is_administrator:
            return redirect(url_for('admin.list_services'))
        else:
            return redirect(url_for('main.dashboard'))
    return render_template('smanager/activate.html', form=form, service=service, ppm=ppm, total=(ppm * service.period), currency=owner.currency)

