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 vmanager
from .forms import DeployForm
from .. import db
from ..email import send_email
from ..models import User, Role, Product, Deployment, contact_proxmaster, Contract, Domain
from ..decorators import admin_required, permission_required

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

def randstr(n):
    return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(n))

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

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

#APP STORE
@vmanager.route('/market/<int:group_id>', methods=['GET'])
@login_required
def market(group_id=0):
    page = { 'title': 'Market' }
    allproducts = Product.get_products()
    allgroups = current_app.config['GROUPS']

    if group_id == 0:
        return render_template('vmanager/market.html', groups=allgroups, products=allproducts)

    filtered_products = {}
    for key, value in allproducts.items():
        if value['group'] == group_id:
            filtered_products[key] = value

    if filtered_products == {}:
        abort(404)
    return render_template('vmanager/marketgroup.html', groupname=allgroups[group_id], products=filtered_products)


@vmanager.route('/deploy/<int:product_id>', methods=['GET', 'POST'])
@login_required
def deploy(product_id=None):
    #if current_user.wallet < 20:
    #    flash('Недостатъчно средства в сметката за тази операция')
    #    return redirect(url_for('uinvoice.addfunds'))

    if current_user.name is None:
        flash('Моля обновете информацията за профила')
        return redirect(url_for('uinvoice.profile'))
        
    page = { 'title': 'Deploy' }
    try:
        product = Product.get_products()[product_id]
    except:
        print('unknown product {}'.format(product_id))
        abort(404)
    product_pic = '..' + product['img']
    product_name = product['name']
    product_description = product['description']

    product_cpu = product['cpu']
    product_mem = product['mem']
    product_hdd = product['hdd']
    product_recipe = product['recipe']

    hostname = 'deploy-{}.local'.format(randstr(6))

    form = DeployForm(servername=hostname, cpu=product_cpu, mem=product_mem, hdd=product_hdd, recipe=product_recipe)
    form.region.choices = current_app.config['REGIONS']
    form.recipe.choices = current_app.config['RECIPES']

    if current_user.confirmed and form.validate_on_submit():
        client_id = current_user.pid
        data = { 'clientid': str(client_id),
                 'clientname': str(current_user.name),
                 'clientemail': str(current_user.email),
                 'hostname': str(form.servername.data),
                 'vmpass': form.vmpassword.data,
                 'region': form.region.data,
                 'vps_type': 'kvm',
                 'vps_recipe': form.recipe.data,
                 'vps_cpu': form.cpu.data,
                 'vps_mem': form.mem.data,
                 'vps_hdd': form.hdd.data,
                 'vps_ipv4': '1' }

        try:
            query = contact_proxmaster(data, 'vmcreate')
        except:
            flash('Region unreachable! Please try again later...')
            return redirect(url_for('vmanager.index'))
 
        if query is not None:
            cubeid = query['cube']
            deployment = Deployment(user_id=client_id, product_id=product_id, machine_alias=form.servername.data, machine_id=cubeid, machine_cpu=form.cpu.data, machine_mem=form.mem.data, machine_hdd=form.hdd.data, date_expire=(datetime.utcnow() + timedelta(days=30)), enabled=True)
            db.session.add(deployment)
            db.session.commit()

            flash('Deploy requested.')
        else:
            flash('Deploy cancelled! Please try again later...') 

        return redirect(url_for('vmanager.index'))

    return render_template('vmanager/deploy.html', page=page, form=form, product_id=product_id, product_pic=product_pic, product_name=product_name, product_description=product_description, product_recipe=product_recipe)


#COMMAND AND CONTROL
@vmanager.route("/dashboard", methods=['GET', 'POST'])
@login_required
def dashboard():
    deployments = current_user.inv_deployments.order_by(Deployment.date_created.desc()).all()
    
    inv_deployments = []
    for invcls in deployments:
        if invcls.enabled == True:
            inv_deployments.extend([invcls.machine_id])
    #if not inv_deployments:
    #    return render_template('vmanager/empty_dashboard.html')

    rrd = {}
    statuses = {}
    for cubeid in inv_deployments:
        rrd[cubeid] = {}
        try:
            query = contact_proxmaster({}, 'vmrrd', cubeid)
        except:
            flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid)))
            send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid), 
                       'vmanager/email/adm_unreachable', user=current_user, cubeid=cubeid)

        graphs_list = ['net', 'cpu', 'mem', 'hdd']
        try: 
            for graph in graphs_list:
                raw = query[graph]['image'].encode('raw_unicode_escape')
                rrd[cubeid][graph] = base64.b64encode(raw).decode()
            status = { cubeid : query['status'] }
            statuses.update(status)
        except Exception as e:
            print(e)
            flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid)))
            send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid), 
                                          'vmanager/email/adm_unreachable', user=current_user, cubeid=cubeid )

    contracts = current_user.inv_contracts.order_by(Contract.date_created.desc()).all()
    #inv_contracts = []
    #for invcls in contracts:
    #    if invcls.enabled == True:
    #        inv_contracts.extend([invcls.template])
    
    domains = current_user.inv_domains.order_by(Domain.date_created.desc()).all()
    #inv_domains = []
    #for invcls in domains:
    #    if invcls.enabled == True:
    #        inv_domains.extend([invcls.fqdn])

    #print(statuses)

    return render_template('vmanager/dashboard.html', rrd=rrd, status=statuses, inv_deployments=deployments, inv_contracts=contracts, inv_domains=domains)

@vmanager.route('/vmvnc/<int:vmid>')
@login_required
def vnc(vmid=0):
    result = current_user.inv_deployments.order_by(Deployment.date_created.desc()).all()
    inventory = []
    for invcls in result:
        if invcls.enabled == True:
            inventory.extend([invcls.machine_id])

    #checks if current user owns this vmid
    if not vmid in inventory:
        print('WARNING: user does not own vmid: ' + str(vmid))
        #TODO: log ips
    else:
        data = {}
        db_result = contact_proxmaster(data, 'vmvnc', vmid)
        #return render_template('vmanager/vnc.html', url=db_result['url'])

        return redirect(db_result['url'])
    abort(404)

valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop']

@vmanager.route('/<cmd>/<int:vmid>')
@login_required
def command(cmd=None, vmid=0):
    #checks whether this is a valid command
    if not cmd in valid_commands:
        print('WARNING: ' + cmd + ' is not a valid command!')
        abort(404)

    #if cmd == 'vmstart' and current_user.wallet < 3.0:
    #    flash('Недостатъчно средства в сметката за тази операция')
    #    return redirect(url_for('uinvoice.addfunds'))

    result = current_user.inv_deployments.order_by(Deployment.date_created.desc()).all()
    inventory = []
    for invcls in result:
        if invcls.enabled == True:
            inventory.extend([invcls.machine_id])

    #checks if current user owns this vmid
    if not vmid in inventory:
        print('WARNING: user id:{} does not own cube id:{}'.format(current_user.pid, vmid))
    else:
        data = {}
        db_result = contact_proxmaster(data, cmd, vmid)
        #print(db_result)
    #TODO: log ips
    abort(404)


