import argparse
import datetime

import cv2 as cv
import dv_processing as dv

parser = argparse.ArgumentParser(
    description='Show a preview of a stereo event stream from a pair of time-synchronized iniVation cameras.')

args = parser.parse_args()

cameras = dv.io.camera.discover()
if len(cameras) < 2:
    raise RuntimeError("Unable to discover two cameras")

# Open the cameras
leftCamera = dv.io.camera.openSync(cameras[0])
rightCamera = dv.io.camera.openSync(cameras[1])

dv.io.camera.synchronizeAnyTwo(leftCamera, rightCamera)

leftVis = dv.visualization.EventVisualizer(leftCamera.getEventResolution())
rightVis = dv.visualization.EventVisualizer(rightCamera.getEventResolution())

# Create the preview windows
cv.namedWindow("Left", cv.WINDOW_NORMAL)
cv.namedWindow("Right", cv.WINDOW_NORMAL)

slicer = dv.StereoEventStreamSlicer()

keepRunning = True


def preview(left, right):
    cv.imshow("Left", leftVis.generateImage(left))
    cv.imshow("Right", rightVis.generateImage(right))
    if cv.waitKey(2) == 27:
        global keepRunning
        keepRunning = False


slicer.doEveryTimeInterval(datetime.timedelta(milliseconds=33), preview)

while keepRunning:
    # if reading fails, just pass an empty event store
    slicer.accept(leftCamera.getNextEventBatch() or dv.EventStore(), rightCamera.getNextEventBatch() or dv.EventStore())
