from collections import deque
import random

class SongQueue:
    def __init__(self):
        self.items = []
        self.history = deque(maxlen=20)
        self.infinite_loop = False

    def add(self, song):
        self.items.append(song)
        return len(self.items)

    def current(self):
        return self.items[0] if self.items else None

    def next(self):
        if not self.items:
            return None

        current = self.items[0]
        self.history.appendleft(current)

        if current.loop_left > 0:
            current.loop_left -= 1
            return current

        if self.infinite_loop:
            return current

        self.items.pop(0)
        return self.current()

    def previous(self):
        if not self.history:
            return None
        prev = self.history.popleft()
        self.items.insert(0, prev)
        return prev

    def shuffle(self):
        if len(self.items) <= 1:
            return False
        current = self.items.pop(0)
        random.shuffle(self.items)
        self.items.insert(0, current)
        return True

    def clear(self):
        self.items.clear()
        self.history.clear()
        self.infinite_loop = False
      
