"""result_thread.py: process results from feature detector thread.

Most of the result processing means emitting the result to a websocket.
"""
from threading import Thread

from feature_detection import Cmd, Rslt


def init_in_connections(flask_app, socketio, command_queue):
    """
    Initialize the routes and incoming web sockets.

    Input Arguments:
    Flask: flask_app     -- Flask server object
    SocketIO: socketio   -- SocketIO object connected to the flask_app
    Queue: command_queue -- Queue of commands to send the processing thread
    """
    @flask_app.route('/')
    def index():
        return('Hello, World!')

    @socketio.on('type')
    def set_data_type(type):
        """Set the type of data that will be processed (ECG or PPG)"""
        command_queue.put((Cmd.TYPE, str(type)))

    @socketio.on('data')
    def process_data(data):
        """ Send data to be analyzed by the feature detector. data can be a
        a list or a scalar.
        """
        if not isinstance(data, list):
            data = [data]
        command_queue.put((Cmd.DATA, data))


class ResultThread(Thread):
    """
    Thread to process the results from the feature detector thread.

    Input Arguments:
    SocketIO: socketio   -- SocketIO object connected to the flask_app
    Queue: command_queue -- Queue of commands to send the processing thread
    Queue: results_queue -- Queue of results from the processing thread
    """

    def __init__(self, socketio, commands, results):
        Thread.__init__(self, daemon=True)

        self.socketio = socketio
        self.command_queue = commands
        self.result_queue = results

    def run(self):
        """Main loop of the processing results thread."""
        while True:
            result = self.result_queue.get()
            if result[0] == Rslt.SYST:
                # scalar containing the systole index
                self.socketio.emit(result[0].value, int(result[1][0]))
            elif result[0] == Rslt.DIAS:
                # scalar containing the diastole index
                self.socketio.emit(result[0].value, int(result[1][0]))
            elif result[0] == Rslt.INST_HR:
                # list containing the instantaneous HR index and it's value
                self.socketio.emit(result[0].value,
                                   [int(result[1][0]), float(result[1][1])])
            elif result[0] == Rslt.AVG_HR:
                # list containing the average HR index and it's value
                self.socketio.emit(result[0].value,
                                   [int(result[1][0]), float(result[1][1])])
            self.result_queue.task_done()
