from flask import Flask, render_template, request

app = Flask(__name__)
app.config["DEBUG"] = True

COMMAND_BUFFER = 5
FRAME_BUFFER = 5
USERS = ['your_name', 'other_name']

# store in memory
commands = {}
images = {}
has_new = {}
for u in USERS:
    commands[u] = []
    images[u] = []
    has_new[u] = [0,0]

@app.route("/", methods=["GET"])
def index():
    return 'Put something nice here.'

@app.route('/<name>/post_command', methods=['POST'])
def post_command(name):
    if name != 'your_name' and name !='other_name':
        return 'user does not exist'
    data = request.form['code']
    if len(commands[name])<COMMAND_BUFFER:
        commands[name].append(data)
    else:
        commands[name][-1] = data
    has_new[name][1] = 1
    return 'command received: ' + str(data)  + ', has_new: ' + str(has_new[name][1])

@app.route('/<name>/get_command', methods=['GET'])
def get_command(name):
    if name != 'your_name' and name !='other_name':
        return 'user does not exist'
    if (has_new[name][1]):
        has_new[name][1] = 0
        return commands[name][-1]
    else:
        return ''

@app.route('/<name>/post_frame', methods=['POST'])
def post_frame(name):
    if name != 'your_name' and name !='other_name':
        return 'user does not exist'
    data = request.data.decode('utf-8')
    if len(images[name])<FRAME_BUFFER:
        images[name].append(data)
    else:
        images[name][-1] = data
    has_new[name][0] = 1
    return 'image received: ' + str(len(data)) + ', has_new: ' + str(has_new[name][0])

@app.route('/<name>/get_frame', methods=['GET'])
def get_frame(name):
    if name != 'your_name' and name !='other_name':
        return 'user does not exist'
    if (has_new[name][0]):
        has_new[name][0] = 0
        return 'data:image/jpeg;base64,' + images[name][-1]
    else:
        return ''

@app.route('/<name>/robot_stream')
def robot_stream(name):
    if name != 'your_name' and name !='other_name':
        return 'this user does not exist'
    return render_template('robot_stream.html', username=name)