import inspect

from .cameraserver import CameraServer


def run(grip_pipeline):
    """
    A function that can be used to run python image processing code
    as generated by GRIP
    """

    if inspect.isclass(grip_pipeline):
        grip_pipeline = grip_pipeline()

    cs = CameraServer.getInstance()
    cs.enableLogging()

    cs.startAutomaticCapture()
    cvSink = cs.getVideo()

    outputStream = None
    img = None

    while True:
        time, img = cvSink.grabFrame(img)
        if time == 0:
            if outputStream:
                outputStream.notifyError(cvSink.getError())

            continue

        # Process it with GRIP
        out_img = grip_pipeline.process(img)
        if out_img is not None:
            try:
                outputStream.putFrame(out_img)
            except AttributeError:
                if outputStream is None:
                    outputStream = cs.putVideo("GRIP", img.shape[1], img.shape[0])
                else:
                    raise
