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_debug_queries

from . import admin
from .forms import ChargeForm, Addr2PoolForm, OrderForm

from .. import db
from ..email import send_email
from ..models import User, Transaction, Order, Server, Deployment, Service, Region, Address, Domain, contact_proxmaster
from ..decorators import admin_required, permission_required

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

#@admin.before_app_request
#def before_request():
#    g.user = current_user
#    print('current_user: %s, g.user: %s, leaving bef_req' % (current_user, g.user))

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

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

@admin.route("/listorders", methods=['GET', 'POST'])
@fresh_login_required
@admin_required
def list_orders():
    NewOrders = Order.query.filter_by(status='new').all()
    AcceptedOrders = Order.query.filter_by(status='accepted').all()
    return render_template('admin/list_orders.html', neworders=NewOrders, oldorders=AcceptedOrders)

@admin.route("/listdeployments", methods=['GET'])
@fresh_login_required
@admin_required
def list_deployments():
    AllDeploymentProtected = Deployment.query.filter_by(deleted=False).order_by(Deployment.daysleft.asc()).all()
    return render_template('admin/list_deployments.html', deployments=AllDeploymentProtected)

@admin.route("/listservices", methods=['GET'])
@fresh_login_required
@admin_required
def list_services():
    allservices = Service.query.filter_by(deleted=False).order_by(Service.daysleft.asc()).all()
    return render_template('admin/list_services.html', services=allservices)

@admin.route("/listdomains", methods=['GET'])
@fresh_login_required
@admin_required
def list_domains():
    alldomains = Domain.query.filter_by(deleted=False).order_by(Domain.daysleft.asc()).all()
    return render_template('admin/list_domains.html', domains=alldomains)

@admin.route("/listarchive", methods=['GET'])
@fresh_login_required
@admin_required
def list_archive():
    deployments = Deployment.query.filter_by(protected=False).order_by(Deployment.daysleft.asc()).all()
    services = Service.query.filter_by(deleted=True).all()
    domains = Domain.query.filter_by(deleted=True).all()
    return render_template('admin/list_archive.html', deployments=deployments, services=services, domains=domains)

@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, current_app.config['ITEMS_PER_PAGE'], error_out=False)
    return render_template('admin/list_users.html', users=sqlquery.items, page=page)

@admin.route("/charge/<int:user_pid>", methods=['GET', 'POST'])
@fresh_login_required
@admin_required
def charge(user_pid=0):
    cuser = User.query.filter_by(pid=user_pid).first()
    form = ChargeForm()
    if form.validate_on_submit():
        transaction = Transaction(user_id=int(cuser.pid), description='Account charged by staff', value=float(form.amount.data))
        db.session.add(transaction)
        db.session.commit()

        cuser.wallet += float(form.amount.data)
        db.session.add(cuser)
        db.session.commit()
        return redirect(url_for('admin.list_users'))
    return render_template('admin/charge.html', form=form, usr=cuser)

@admin.route("/listaddresses", methods=['GET'])
@fresh_login_required
@admin_required
def list_addresses():
    alladdresses = Address.query.all()
    alladdrlist = []
    for addr in alladdresses:
        alladdrlist.append(addr.ip)
    ipobjs = sorted(ipaddress.ip_address(addr) for addr in alladdrlist)
    ipnrml = []
    for ipobj in ipobjs:
        ipnrml.append(str(ipobj))
    alladdr = sorted(alladdresses, key=lambda o: ipnrml.index(o.ip))
    return render_template('admin/list_addresses.html', addresses=alladdr)

@admin.route("/addr2pool", methods=['GET', 'POST'])
@fresh_login_required
@admin_required
def addr2pool():
    alladdrlist = []
    alladdr = Address.query.all()
    for addr in alladdr:
        alladdrlist.append(str(addr.ip))
    #current_app.logger.info('Current IP pool: {}'.format(alladdrlist))
    form = Addr2PoolForm()
    if form.validate_on_submit():
        if form.ip.data in alladdrlist:
            flash('IP address {} is already in the pool!'.format(form.ip.data))
            return redirect(url_for('admin.addr2pool'))
        address = Address(ip=form.ip.data, rdns=form.rdns.data, region_id=form.region.data, enabled=True, reserved=form.reserved.data) 
        db.session.add(address)
        db.session.commit()
        flash('Address {} added to region {}'.format(form.ip.data, form.region.data))
        return redirect(url_for('admin.addr2pool'))
    return render_template('admin/addr2pool.html', form=form, alladdresses=alladdrlist) 

@admin.route("/listservers", methods=['GET'])
@fresh_login_required
@admin_required
def list_servers():
    allservers = Server.query.all()
    return render_template('admin/list_servers.html', servers=allservers)

@admin.route("/listtransactions/", defaults={'page': 1})
@admin.route("/listtransactions/<int:page>", methods=['GET'])
@fresh_login_required
@admin_required
def list_transactions(page):
    sqlquery = Transaction.query.order_by(Transaction.date_created.desc()).paginate(page, current_app.config['ITEMS_PER_PAGE'], error_out=False)
    return render_template('admin/list_transactions.html', transactions=sqlquery.items, page=page)

@admin.route("/transaction/<int:user_pid>", methods=['GET'])
@fresh_login_required
@admin_required
def transaction(user_pid=0):
    cuser = User.query.filter_by(pid=user_pid).first()
    transactions = cuser.inv_transactions.order_by(Transaction.date_created.desc()).limit(20)

    labelslist = ['today']
    translist = [cuser.wallet]
    prevvalue = cuser.wallet
    for tr in transactions:
        labelslist.insert(0, str(tr.date_created.strftime('%d.%m')))
        translist.insert(0, prevvalue - tr.value)
        prevvalue -= tr.value

    if len(labelslist) <= 1:
        labelslist.insert(0, 'before')
        translist.insert(0, 0)

    #current_app.logger.info('[{}] transactions: {} {} '.format(cuser.email, translist, labelslist))
    return render_template('uinvoice/transactions.html', transactions=transactions, translist=translist, labelslist=labelslist, cuser=cuser)

