import cv2
import imageio


class FrameBuffer(object):

    def __init__(self, size):
        self.size = size
        self.items = []

    def is_empty(self):
        return len(self.items) == 0

    def get_size(self):
        return len(self.items)

    def push(self, frame):
        self.items.append(frame)
        if self.get_size() > self.size:
            self.items.pop(0)

    def get_frames(self):
        return self.items

    def write_gif(self, filename):
        with imageio.get_writer(filename, mode='I') as writer:
            for frame in self.items:
                writer.append_data(frame)

    def dump(self):
        self.items = []

    def write_mp4(self, filename, width, height, fps=25):
        print("Schreibe mp4 Datei")
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(filename, fourcc, fps, frameSize=(width, height))

        for frame in self.items:
            out.write(frame)

        out.release()