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 main
from .. import db
from ..email import send_email
from ..models import User, Permission, Server, Deployment, Service, Region, Address, Domain, contact_proxmaster

import base64

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

#STATIC PAGES
@main.route("/", methods=['GET'])
def index():
    allservers = Server.query.filter_by(enabled=True)
    return render_template('main/index.html', servers=allservers)

@main.route("/chat", methods=['GET'])
def chat():
    return render_template('main/livechat.html')

#@main.route("/aboutus", methods=['GET'])
#def about():
#    return render_template('main/aboutus.html')

@main.route('/domaincheck', methods=['GET'])
def domaincheck():
    return render_template('main/domaincheck.html')

@main.route("/terms", methods=['GET'])
def terms():
    return render_template('main/terms.html')

#APP STORE
@main.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('main/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('main/marketgroup.html', groupname=allgroups[group_id], products=filtered_products)

