from app import logger, socketio
from flask_login import login_required
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from .forms import TestForm
import io


@socketio.on('submit-test-form')
@login_required
def recv_test_form(data):
    logger.warning("data_received")
    filename = secure_filename(data['file-wrapper']['name'])
    stream = io.BytesIO(data['file-wrapper']['bytes'])
    file = FileStorage(filename=filename, stream=stream)
    data['file'] = file
    test_form = TestForm(data=data)
    if test_form.validate():
        socketio.emit('submit-test-form', {'msg': {},
                                           'status': 201})
    else:
        socketio.emit('submit-test-form', {'msg': test_form.errors,
                                           'status': 400})
