import logging
import math
from typing import Iterator, Union

from pojagi_dsp.series_frame import (SeriesFrameFilter,
                                     SeriesFramePackage)

logger = logging.getLogger(__name__)


class Looping(SeriesFrameFilter):
    """
    Filter that loops through the input reader's frames until it reaches
    the given :param:`iterations`
    """

    def __init__(
        self,
        iterations: Union[int, float] = math.inf,
        **kwargs,
    ) -> None:
        """
        :param:`iterations` - number of times to loop through the `frames`.
        """
        super().__init__(**kwargs)
        self.iterations = iterations
        self.iteration = 0

    def increment(self) -> None:
        """Override to react to `iteration` increment."""
        self.iteration += 1
        logger.debug(
            f"Loop incremented ({self.sft_info.alias}): {self.iteration}"
        )

    def frames(self) -> Iterator[SeriesFramePackage]:
        while self.iteration < self.iterations:
            for pkg in self.reader.frames():
                yield pkg
            self.increment()
