from queue import Queue
import numpy as np
import cv2

from MQTTObserver import MQTTObserver

class ESP32Cam(MQTTObserver):

    def __init__(self, camera_id: str):
        self._camera_id = camera_id
        self._images = Queue(maxsize=5)


    def update(self, message): 
        raw_picture = message.payload
        np_image = np.frombuffer(raw_picture, np.uint8)
        image = cv2.imdecode(np_image, cv2.IMREAD_COLOR)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        if self._images.full():
            self._images.get()
        self._images.put(image)

    
    def get_frame(self):
        if not self._images.empty():
            image = self._images.get()
            
            if len(self._images.queue) == 1:
                self._images.put(image)
            
            return image
        return None
        

    
