# IMPORTS
from flask import Flask, render_template, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_login import current_user, login_required
from flask_mail import Mail 
import os
from dotenv import load_dotenv 
load_dotenv(verbose=True)
from flask.json import JSONEncoder

# CONFIG
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(os.getenv('APP_SETTINGS'))



import redis
from rq import Queue
import time

r = redis.Redis()
q = Queue(connection=r)


db = SQLAlchemy(app) 
with app.app_context():
    db.init_app(app)
    
bcrypt = Bcrypt(app)
mail = Mail(app)
 

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "users.login"

from project.models import User, Items


@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == int(user_id)).first()


# BLUEPRINTS
from project.users.views import users_blueprint
from project.items.views import items_blueprint
from project.cloud.views import cloud_blueprint
from project.keypair.views import keypair_blueprint
from project.secgroup.views import secgroup_blueprint
from project.support.views import support_blueprint
from project.billing.views import billing_blueprint

# template blueprints
app.register_blueprint(users_blueprint)
app.register_blueprint(items_blueprint)

# Cloud blueprints
app.register_blueprint(cloud_blueprint,url_prefix='/cloud')
app.register_blueprint(keypair_blueprint, url_prefix='/keypair')
app.register_blueprint(secgroup_blueprint, url_prefix='/secgroup')

# billing, support Blueprint
app.register_blueprint(support_blueprint, url_prefix='/support')
app.register_blueprint(billing_blueprint, url_prefix='/billing')


@app.route('/', methods=["GET"])
def landing():
    return render_template('new/landing_ori.html')
    
# ROUTES
@app.route('/dashboard', methods=['GET', 'POST'])
@login_required
def home():
    """Render homepage"""
    all_user_items = Items.query.filter_by(user_id=current_user.id)
    return render_template('home.html', items=all_user_items)

# ERROR PAGES
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(403)
def page_forbidden(e):
    return render_template('403.html'), 403


@app.errorhandler(410)
def page_gone(e):
    return render_template('410.html'), 410
