# Path: pybar/daq/fei4_raw_data.py
# def send_data(socket, data, scan_parameters={}, name='ReadoutData'):
#     '''Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
#     '''
#     if not scan_parameters:
#         scan_parameters = {}
#     data_meta_data = dict(
#         name=name,
#         dtype=str(data[0].dtype),
#         shape=data[0].shape,
#         timestamp_start=data[1],  # float
#         timestamp_stop=data[2],  # float
#         readout_error=data[3],  # int
#         scan_parameters=scan_parameters  # dict
#     )
#     try:
#         socket.send_json(data_meta_data, flags=zmq.SNDMORE | zmq.NOBLOCK)
#         socket.send(data[0], flags=zmq.NOBLOCK)  # PyZMQ supports sending numpy arrays without copying any data
#     except zmq.Again:
#         pass


import time
import numpy as np
import tables as tb
import zmq
import progressbar
from subprocess import Popen
from pybar.daq.fei4_raw_data import send_data

'''This example shows the power of a fast raw data analysis and a data taking system where no data is discarded.
A raw data file is loaded and and data chunks are sent to the online monitor. These chunks are sent with the same speed
as it was done during data taking. This script can used to replay existing raw data files.

The online monitor will be automatically started when calling this script.
'''





def transfer_file(file_name, socket):  # Function to open the raw data file and sending the readouts periodically
    with tb.open_file(file_name, mode="r") as in_file_h5:
        meta_data = in_file_h5.root.meta_data[:]
        raw_data = in_file_h5.root.raw_data[:]
        try:
            scan_parameter_names = in_file_h5.root.scan_parameters.dtype.names
        except tb.NoSuchNodeError:
            scan_parameter_names = None
        progress_bar = progressbar.ProgressBar(widgets=['', progressbar.Percentage(), ' ', progressbar.Bar(marker='*', left='|', right='|'), ' ', progressbar.AdaptiveETA()], maxval=meta_data.shape[0], term_width=80)
        progress_bar.start()
        for index, (index_start, index_stop) in enumerate(np.column_stack((meta_data['index_start'], meta_data['index_stop']))):
            data = []
            data.append(raw_data[index_start:index_stop])
            data.extend((float(meta_data[index]['timestamp_start']), float(meta_data[index]['timestamp_stop']), int(meta_data[index]['error'])))
            if scan_parameter_names is not None:
                scan_parameter_value = [int(value) for value in in_file_h5.root.scan_parameters[index]]
                send_data(socket, data, scan_parameters=dict(zip(scan_parameter_names, scan_parameter_value)))
            else:

# Path: pybar/daq/fei4_raw_data.py
# def send_data(socket, data, scan_parameters={}, name='ReadoutData'):
#     '''Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
#     '''
#     if not scan_parameters:
#         scan_parameters = {}
#     data_meta_data = dict(
#         name=name,
#         dtype=str(data[0].dtype),
#         shape=data[0].shape,
#         timestamp_start=data[1],  # float
#         timestamp_stop=data[2],  # float
#         readout_error=data[3],  # int
#         scan_parameters=scan_parameters  # dict
#     )
#     try:
#         socket.send_json(data_meta_data, flags=zmq.SNDMORE | zmq.NOBLOCK)
#         socket.send(data[0], flags=zmq.NOBLOCK)  # PyZMQ supports sending numpy arrays without copying any data
#     except zmq.Again:
#         pass


# Path: examples/example_online_monitor/replay_data.py
import time
import numpy as np
import tables as tb
import zmq
import progressbar
from subprocess import Popen
from pybar.daq.fei4_raw_data import send_data

'''This example shows the power of a fast raw data analysis and a data taking system where no data is discarded.
A raw data file is loaded and and data chunks are sent to the online monitor. These chunks are sent with the same speed
as it was done during data taking. This script can used to replay existing raw data files.

The online monitor will be automatically started when calling this script.
'''





def transfer_file(file_name, socket):  # Function to open the raw data file and sending the readouts periodically
    with tb.open_file(file_name, mode="r") as in_file_h5:
        meta_data = in_file_h5.root.meta_data[:]
        raw_data = in_file_h5.root.raw_data[:]
        try:
            scan_parameter_names = in_file_h5.root.scan_parameters.dtype.names
        except tb.NoSuchNodeError:
            scan_parameter_names = None
        progress_bar = progressbar.ProgressBar(widgets=['', progressbar.Percentage(), ' ', progressbar.Bar(marker='*', left='|', right='|'), ' ', progressbar.AdaptiveETA()], maxval=meta_data.shape[0], term_width=80)
        progress_bar.start()
        for index, (index_start, index_stop) in enumerate(np.column_stack((meta_data['index_start'], meta_data['index_stop']))):
            data = []
            data.append(raw_data[index_start:index_stop])
            data.extend((float(meta_data[index]['timestamp_start']), float(meta_data[index]['timestamp_stop']), int(meta_data[index]['error'])))
            if scan_parameter_names is not None:
                scan_parameter_value = [int(value) for value in in_file_h5.root.scan_parameters[index]]
                send_data(socket, data, scan_parameters=dict(zip(scan_parameter_names, scan_parameter_value)))
            else:

                send_data(socket, data)
