from flask import *
from flask_restful import *
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, inspect, or_
from config.config import ConfigClass
from werkzeug.exceptions import HTTPException
from functools import wraps
import os
from datetime import datetime, timedelta
from flask_toastr import Toastr
from functools import wraps
from werkzeug.utils import secure_filename
from sqlalchemy import func, inspect, or_
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required, JWTManager
from flask_login import *
from flask_mail import Mail, Message

app = Flask(__name__, template_folder='templates', static_folder='static')
api = Api(app)

app.config.from_object(__name__+'.ConfigClass')

db = SQLAlchemy(app)
app.config['SESSION_SQLALCHEMY'] = db
app.config['CORS_HEADERS'] = 'Content-Type'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'docx', 'png', 'jpg', 'jpeg', 'gif'}

login_manager = LoginManager()

login_manager.init_app(app)

mail = Mail(app)

from models.models import *
# from models.oldModel import *

jwt = JWTManager(app)
# CORS(app, origins=['http://localhost:8081'], allow_headers='*')
CORS(app, origins='*', allow_headers='*')
toastr = Toastr(app)

@login_manager.user_loader
def user_loader(email):
    # print(email)
    if email:
        return Users.query.filter_by(email = email).first()

@app.route('/logout')
def logout():
    logout_user()
    flash('You have been logged out successfully', 'info')
    return redirect('/login')

@app.route('/make-migration')
def migrations():
    db.create_all()
    return redirect('/login')

@app.route("/migrate_database")
def migrate_db():
    db.create_all(bind_key=[None, 'oldDB'])
    return jsonify(message = "Database tables created successfully")

@login_manager.unauthorized_handler
def unauthorized_handler():
    flash('You need to login to access this page', 'error')
    return redirect('/login')

@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email:
        return Users.query.get(email)

@app.after_request
def add_header(response):
    if session.get('TOKEN', None):
        response.set_cookie('access_token_cookie', session.get('TOKEN'))
    return response

@app.errorhandler(HTTPException)
def error_handler(e):
    response = e.get_response()
    gh = request.environ.get('HTTP_USER_AGENT')
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
        'source': gh
    })
    response.content_type = "application/json"
    
    return make_response(response, e.code)
