# coding: utf-8
"""Expose data to different interface

ZMQStream explose to a ZeroMQ socket in a REQ/REP pattern.

Copyright (c) 2017, European X-Ray Free-Electron Laser Facility GmbH
All rights reserved.

You should have received a copy of the 3-Clause BSD License along with this
program. If not, see <https://opensource.org/licenses/BSD-3-Clause>
"""

from argparse import ArgumentParser
import os.path as osp
from queue import Queue
from threading import Event, Thread
from time import time

import msgpack
import numpy as np
import zmq

from .reader import RunDirectory, H5File

__all__ = ['ZMQStreamer', 'serve_files']


class REPInterface(Thread):
    def __init__(self, context, port, buffer):
        super(REPInterface, self).__init__()
        self.context = context
        self.port = port
        self.buffer = buffer
        self._stop_event = Event()

    def run(self):
        interface = self.context.socket(zmq.REP)
        try:
            interface.bind('tcp://*:{}'.format(self.port))

            while not self.stopped():
                req = interface.recv()
                if req != b'next':
                    raise RuntimeError('Unknown request:', req)
                interface.send_multipart(self.buffer.get())
        finally:
            interface.setsockopt(zmq.LINGER, 0)
            interface.close()

    def stop(self):
        self._stop_event.set()

    def stopped(self):