from __future__ import annotations

__all__ = ["SequentialDataFrameTransformer"]

from collections.abc import Sequence

from coola.utils import str_indent, str_sequence
from pandas import DataFrame

from flamme.transformer.df.base import (
    BaseDataFrameTransformer,
    setup_dataframe_transformer,
)


class SequentialDataFrameTransformer(BaseDataFrameTransformer):
    r"""Implements a ``pandas.DataFrame`` transformer to apply
    sequentially several transformers.

    Args:
        transformers (``Sequence``): Specifies the transformers or
            their configurations.

    Example usage:

    .. code-block:: pycon

        >>> import pandas as pd
        >>> from flamme.transformer.df import (
        ...     Sequential,
        ...     StripString,
        ...     ToNumeric,
        ... )
        >>> transformer = Sequential(
        ...     [
        ...         StripString(columns=["col1", "col3"]),
        ...         ToNumeric(columns=["col1", "col2"]),
        ...     ]
        ... )
        >>> transformer
        SequentialDataFrameTransformer(
          (0): StripStringDataFrameTransformer(columns=('col1', 'col3'))
          (1): ToNumericDataFrameTransformer(columns=('col1', 'col2'))
        )
        >>> df = pd.DataFrame(
        ...     {
        ...         "col1": [1, 2, 3, 4, 5],
        ...         "col2": ["1", "2", "3", "4", "5"],
        ...         "col3": ["a ", " b", "  c  ", "d", "e"],
        ...         "col4": ["a ", " b", "  c  ", "d", "e"],
        ...     }
        ... )
        >>> df
           col1 col2   col3   col4
        0     1    1     a      a
        1     2    2      b      b
        2     3    3    c      c
        3     4    4      d      d
        4     5    5      e      e
        >>> df = transformer.transform(df)
        >>> df
           col1 col2 col3   col4
        0     1    1    a     a
        1     2    2    b      b
        2     3    3    c    c
        3     4    4    d      d
        4     5    5    e      e
    """

    def __init__(self, transformers: Sequence[BaseDataFrameTransformer | dict]) -> None:
        self._transformers = tuple(
            setup_dataframe_transformer(transformer) for transformer in transformers
        )

    def __repr__(self) -> str:
        args = ""
        if self._transformers:
            args = f"\n  {str_indent(str_sequence(self._transformers))}\n"
        return f"{self.__class__.__qualname__}({args})"

    def transform(self, df: DataFrame) -> DataFrame:
        for transformer in self._transformers:
            df = transformer.transform(df)
        return df
