from flask import Flask
from flask import request, jsonify
from flask_cors import CORS
import performance_test

app = Flask(__name__)
CORS(app, supports_credentials=True)
REQUEST_PASSWORD = "test123456"


def return_json(data=None, message="", success=True, status_code=200):
    return jsonify({
        "success": success,
        "message": message,
        "data": data
    }), status_code


def error_catch_and_password_check(func):
    def wrapper(*args, **kwargs):
        try:
            if request.headers.get('password') != REQUEST_PASSWORD:
                return return_json(message="Unauthorized", success=False, status_code=403)

            return func(*args, **kwargs)
        except Exception as e:
            # raise e
            return return_json(message=f"Error: {repr(e)}", success=False, status_code=500)

    wrapper.__name__ = func.__name__
    return wrapper

@app.route('/ping', methods=['GET'])
@error_catch_and_password_check
def ping_request():
    return return_json(message="pong", success=True, status_code=200)

@app.route("/performance_test_get_list", methods=["GET"])
@error_catch_and_password_check
def performance_test_get_list_request():
    per_page = request.args.get("count", default=10000, type=int)
    example_data_limit = request.args.get("example_data_limit", default=10, type=int)
    idx = request.args.get("idx", default=-1, type=int)
    grpc_result, rest_result = performance_test.test_get_main(per_page=per_page, list_data_limit=example_data_limit)
    return return_json({
        "idx": idx,
        "request_count": per_page,
        "grpc": grpc_result,
        "rest": rest_result
    })

@app.route("/performance_test_add_books", methods=["GET"])
@error_catch_and_password_check
def performance_test_add_books_request():
    book_count = request.args.get("count", default=1000, type=int)
    grpc_result, rest_result = performance_test.test_add_main(book_count=book_count)
    idx = request.args.get("idx", default=-1, type=int)
    return return_json({
        "idx": idx,
        "request_count": book_count,
        "grpc": grpc_result,
        "rest": rest_result
    })


if __name__ == "__main__":
    app.run("0.0.0.0", port=9520)
