from flask import Flask, jsonify, request
import random

app = Flask(__name__)


def gen_attachment(size):
    return b'\x00' + bytes([random.randrange(0, 255) for i in range(0, size)]) + b'\x00'


attachment = gen_attachment(4)


def get_attachment_size():
    return len(attachment)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        some_json = request.get_json()
        return jsonify({'you sent': some_json}), 201
    else:
        return jsonify({"about": "Hello world!"})


@app.route('/minimal/', methods=['POST'])
def minimal():
    return jsonify({"Message": "Received"})


@app.route('/load/getbinary/', methods=['POST'])
def get_binary():
    global attachment
    some_json = request.get_json()
    try:
        size = int(some_json['Size'])
    except ValueError:
        print("Size is not an Integer")
        return jsonify({'Error': "Size has to be an Integer"}), 500
    except KeyError:
        print("Size not found")
        return jsonify({'Error': "Size not found"}), 500

    if size > len(attachment):
        attachment = gen_attachment(size)
        return jsonify({'Attachment': attachment.decode('latin-1')}), 200
    else:
        return jsonify({'Attachment': attachment[0:size].decode('latin-1')}), 200


@app.route('/load/sendbinary/', methods=['POST'])
def send_binary():
    some_json = request.get_json()
    try:
        element_attachment = some_json['Attachment']
    except KeyError:
        print("Attachment not found")
        return jsonify({"Error": "Attachment not found"}), 500
    return jsonify({"Response": len(element_attachment)}), 200


if __name__ == '__main__':
    app.run(port=5001)
