from flask import Blueprint
from flask import request as flask_request

from sandbox.yasandbox import context
from sandbox.serviceapi.web.routes import RequestContext
from sandbox.serviceapi.web import middlewares, exceptions
from sandbox.serviceapi.web.routes import http_error_handler, base_error_handler
from load.projects.lunaparkapi.handlers import report, ping
from load.projects.lunaparkapi.web.request import Request as LunaparkApiRequest

try:
    import uwsgi
except ImportError:
    uwsgi = None


__all__ = ('init_api',)


@middlewares.wrap_temporary_errors
def before_request():
    # Create a new context and replace the base one.
    # For statistics collection purpose, do this even for requests to be rejected
    req = LunaparkApiRequest(flask_request, context.current.logger)
    ctx = RequestContext(req)
    context.set_current(ctx)


def init_api(app):

    ping_bp = Blueprint('ping', __name__)
    ping_bp.before_request(before_request)
    ping_bp.add_url_rule('/ping', 'ping', ping.ping)
    ping_bp.errorhandler(exceptions.HttpError)(http_error_handler)
    ping_bp.errorhandler(Exception)(base_error_handler)

    datalens_bp = Blueprint('datalens', __name__)
    datalens_bp.before_request(before_request)
    datalens_bp.add_url_rule('/datalens', 'datalens', report.get_report)
    datalens_bp.errorhandler(exceptions.HttpError)(http_error_handler)
    datalens_bp.errorhandler(Exception)(base_error_handler)

    # the same handler as datalens, used for debugging purpose,
    # should be deleted after integraton test task creation
    report_bp = Blueprint('report', __name__)
    report_bp.add_url_rule('/report', 'report', report.get_report)
    report_bp.errorhandler(exceptions.HttpError)(http_error_handler)
    report_bp.errorhandler(Exception)(base_error_handler)

    app.register_blueprint(ping_bp)
    app.register_blueprint(datalens_bp)
    app.register_blueprint(report_bp)
