<reponame>sachinraina112/flask_app
import logging

from Application import profiler_wc
from flask import Flask, jsonify
from flask_cors import CORS
from swagger_ui import flask_api_doc
from werkzeug.exceptions import HTTPException, InternalServerError, RequestEntityTooLarge

logger = logging.getLogger(__name__)


def add_error_handlers(app):

    @app.errorhandler(Exception)
    def handle_unknown(error):
        logger.exception(error)
        return {"message": "Unknown error occurred, please contact administrator", "success": False}, 500

    @app.errorhandler(InternalServerError)
    def handle_internal_error(error):
        logger.exception(error)
        return {"message": "Internal server error", "success": False, "code": 500}, 500

    @app.errorhandler(HTTPException)
    def handle_http_exception(error):
        logger.exception(error)
        return {"message": error.description, "success": False, "code": error.code}, 500

    @app.errorhandler(RequestEntityTooLarge)
    def handle_large_request_err(error):
        logger.exception(error)
        return {"message": "Request size cannot be greater than 10 MB", "success": False, "code": 417}, 500

    @app.errorhandler(400)
    def handle_bad_request(e):
        logger.warning('Bad request', e)
        return {"message": "Bad request", "success": False}, 400


def add_routes(app):

    @app.route("/heartbeat")
    def heart_beat():
        return jsonify(True)


def create_app():
    app = Flask(__name__)
    app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
    flask_api_doc(app, config_path='swagger.yaml', url_prefix='/market_watch/api/v1/profiler/docs', title='API docs')
    with app.app_context():
        add_error_handlers(app)
        add_routes(app)
        app.register_blueprint(profiler_wc, url_prefix="/market_watch/api/v1/profiler")
    app.url_map.strict_slashes = False
    cors = CORS(app, origins='*')
    return app
