# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from typing import Any, Callable

import torch
from torch import nn


class Lambda(nn.Module):
    """Wrap a Python callable as an ``nn.Module`` that applies it to its input.

    ``f = Lambda(func)`` stores ``func``, and ``out = f(img, *args, **kwargs)`` returns ``func(img, *args, **kwargs)``
    unchecked; it need not be a tensor. Use it to put a plain function into an ``nn.Sequential`` or an augmentation
    container.

    Args:
        func: Callable function.

    Raises:
        TypeError: if ``func`` is not callable; raised from the constructor.

    See Also:
        - :class:`~kornia.augmentation.container.ImageSequential`: chains augmentations; a ``Lambda`` runs in it as one
          step.

    Example:
        >>> import kornia
        >>> x = torch.rand(1, 3, 5, 5)
        >>> f = Lambda(lambda x: kornia.color.rgb_to_grayscale(x))
        >>> f(x).shape
        torch.Size([1, 1, 5, 5])

    """

    def __init__(self, func: Callable[..., Any]) -> None:
        super().__init__()
        if not callable(func):
            raise TypeError(f"Argument func should be callable, got {type(func).__name__!r}")

        self.func = func

    def forward(self, img: torch.Tensor, *args: Any, **kwargs: Any) -> Any:
        """Return ``func(img, *args, **kwargs)``.

        Args:
            img: the first positional argument of ``func``.
            *args: Additional positional arguments forwarded to ``func``.
            **kwargs: Additional keyword arguments forwarded to ``func``.

        Returns:
            Whatever ``func`` returns.

        """
        return self.func(img, *args, **kwargs)
