"""Filter mixin class."""
from __future__ import annotations

import dataclasses as dc
from typing import Any

from .protocols import IsDataset
from .protocols import IsFilteredDataset
from tempora.utils.dataclass import get_args_dict


@dc.dataclass(frozen=True)
class FilterMixin:
    ts_filter: str | None = None
    columns: list[str] | None = None

    def __post_init__(self: IsDataset, _op_dict: dict[str, Any] | None) -> None:  # type: ignore[override]  # noqa
        super().__post_init__(_op_dict=_op_dict)  # type: ignore[safe-super]

    @classmethod
    def from_dataset(
        cls,
        dataset: IsDataset,
        ts_filter: str | None = None,
        columns: list[str] | None = None,
        materialize: bool = False,
    ) -> IsFilteredDataset:
        """Create a filtered version of a dataset.

        Args:
            dataset: The dataset to filter.
            ts_filter: Row filter condition in the form of a SQL WHERE clause
                (e.g."id = '12345' AND model = 'xyz'")
            columns: The specific columns to return.
            materialize: If True materialize the result of the filter operation on the
                server.

        Returns:
            The filtered dataset object.
        """
        args: dict[str, Any] = {}
        for field in dc.fields(dataset):  # noqa
            args[field.name] = getattr(dataset, field.name)

        args['ts_filter'] = ts_filter
        args['columns'] = columns
        args['materialize'] = materialize
        args['_op_dict'] = {'op': 'filter', 'parent': get_args_dict(dataset)}
        return cls(**args)  # type: ignore[return-value]
