from flask import current_app, request
from flask_login import current_user, login_required
from . import socketio
from .decorators import admin_required
from .models import User
import json
import jsonpatch


'''
' A list containing session ids of connected Socket.IO sessions, to keep track
' of all connected sessions, which is used to determine the runtimes of
' associated background tasks.
'''
connected_sessions = []


@socketio.on('connect')
@login_required
def connect():
    '''
    ' The Socket.IO module creates a session id (sid) for each request.
    ' On connect the sid is saved in the connected sessions list.
    '''
    connected_sessions.append(request.sid)


@socketio.on('disconnect')
@login_required
def disconnect():
    '''
    ' On disconnect the session id gets removed from the connected sessions
    ' list.
    '''
    connected_sessions.remove(request.sid)


@socketio.on('user_ressources_init')
@login_required
def subscribe_user_ressources():
    socketio.start_background_task(user_ressource_session_handler,
                                   current_app._get_current_object(),
                                   current_user.id, request.sid)


@socketio.on('foreign_user_ressources_init')
@login_required
@admin_required
def subscribe_foreign_user_ressources(user_id):
    socketio.start_background_task(user_ressource_session_handler,
                                   current_app._get_current_object(),
                                   user_id, request.sid, True)


def user_ressource_session_handler(app, user_id, session_id, foreign=False):
    '''
    ' Sends initial corpus and job lists to the client. Afterwards it checks
    ' every 3 seconds if changes to the initial values appeared. If changes are
    ' detected, a RFC 6902 compliant JSON patch gets send.
    '
    ' NOTE: The initial values are send as a init events.
    '       The JSON patches are send as update events.
    '''
    init_events = {'corpora': 'foreign_corpora_init' if foreign
                   else 'corpora_init',
                   'jobs': 'foreign_jobs_init' if foreign else 'jobs_init'}
    update_events = {'corpora': 'foreign_corpora_update' if foreign
                     else 'corpora_update',
                     'jobs': 'foreign_jobs_update' if foreign
                     else 'jobs_update'}
    with app.app_context():
        # Gather current values from database.
        user = User.query.get(user_id)
        corpora = {corpus.id: corpus.to_dict() for corpus in user.corpora}
        jobs = {job.id: job.to_dict() for job in user.jobs}
        # Send initial values to the user.
        socketio.emit(init_events['corpora'], json.dumps(corpora),
                      room=session_id)
        socketio.emit(init_events['jobs'], json.dumps(jobs), room=session_id)
        while session_id in connected_sessions:
            # Get new values from the database
            new_corpora = {corpus.id: corpus.to_dict() for corpus in user.corpora}
            new_jobs = {job.id: job.to_dict() for job in user.jobs}
            # Compute JSON patches.
            corpora_patch = jsonpatch.JsonPatch.from_diff(corpora, new_corpora)
            jobs_patch = jsonpatch.JsonPatch.from_diff(jobs, new_jobs)
            # In case there are patches, send them to the user.
            if corpora_patch:
                socketio.emit(update_events['corpora'],
                              corpora_patch.to_string(), room=session_id)
            if jobs_patch:
                socketio.emit(update_events['jobs'], jobs_patch.to_string(),
                              room=session_id)
            # Set new values as references for the next iteration.
            corpora = new_corpora
            jobs = new_jobs
            socketio.sleep(3)
