from threading import Thread

from scvf.loops import camera_loop, pipeline_loop, settings_callback
from scvf.util import PipelineManager, ImageContainer, CameraManager, Settings
import numpy

# This flag tells the loop wheather it should run. It is switched to True on start and False on end.
running = False


def start(pipelines, camera_port=0, output_consumer=lambda: None, settings_supplier=lambda x: None,
          width=320, height=240):
    """
        This function starts the CV loop, receiving all the needed parameters.

        Parameters:
            :param pipelines:
                a list of all the pipelines the loop should manage
            :param camera_port:
                the initial
            :param output_consumer
                this is the function that should receive the output generated by the pipeline
                and (optionally) send it to another computer.
            :param settings_supplier:
                this function should process a callback that should be called each time a new settings arrives
                (for more info look into the doc on loops.settings_callback)
            :param width
                the width of the image in pixels
            :param height
                the height of the image in pixels

    """
    global running
    img = ImageContainer()
    pipeline_settings = Settings()
    camera_settings = Settings()

    pipeline_manager = PipelineManager(pipelines)
    camera_manager = CameraManager(port=camera_port, width=width, height=height)

    pipeline_thread = Thread(target=pipeline_loop, args=(img, pipeline_manager, pipeline_settings,
                                                         output_consumer, lambda: running))
    camera_thread = Thread(target=camera_loop, args=(img, camera_manager, camera_settings, lambda: running))
    running = True
    settings_supplier(settings_callback(camera_settings, pipeline_settings))
    pipeline_thread.start()
    camera_thread.start()


def end():
    """
        this function ends the cv loop
    """
    global running
    running = False
