# 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, Dict, Optional

import torch

from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.core.utils import _samples_half_in_float32, _to_device_nonblocking
from kornia.geometry.grid import create_meshgrid
from kornia.geometry.linalg import euclidean_distance
from kornia.geometry.transform import remap


class RandomFisheye(AugmentationBase2D):
    r"""Add a random radial (fisheye) distortion, applied per sample with probability ``p`` (default 0.5).

    ``output = RandomFisheye(...)(input)`` radially distorts each selected image of shape ``(B, C, H, W)``.

    Args:
        center_x: Ranges to sample respect to x-coordinate center with shape (2,).
        center_y: Ranges to sample respect to y-coordinate center with shape (2,).
        gamma: Ranges to sample for the gamma values respect to optical center with shape (2,).
        same_on_batch: apply the same transformation across the batch.
        p: probability of applying the transformation to each sample.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                 to the batch form (False).

    .. image:: _static/img/RandomFisheye.png

    Convention:
        Coordinates are normalized to ``[-1, 1]`` with corner pixel centers at the endpoints.
        At output coordinate ``(x, y)``, let ``r`` be its distance from the sampled center.
        The input sampling coordinate is ``(x * (1 + r**gamma), y * (1 + r**gamma))``:
        the center changes the distance, but scaling is about the coordinate origin.
        Sampling is bilinear with zero padding and ``align_corners=True``; these settings are fixed.
        There is no ``transform_matrix`` or ``inverse``. A ``mask``, keypoint or box data key raises
        ``NotImplementedError`` identifying this augmentation, even at ``p=0``
        (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).

    See Also:
        - :class:`RandomPerspective`: samples a projective rather than radial warp.

    Examples:
        >>> import torch
        >>> img = torch.ones(1, 1, 2, 2)
        >>> center_x = torch.tensor([-.3, .3])
        >>> center_y = torch.tensor([-.3, .3])
        >>> gamma = torch.tensor([.9, 1.])
        >>> out = RandomFisheye(center_x, center_y, gamma)(img)
        >>> out.shape
        torch.Size([1, 1, 2, 2])

    To apply the exact augmenation again, you may take the advantage of the previous parameter state:
        >>> input = torch.randn(1, 3, 32, 32)
        >>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
        >>> (aug(input) == aug(input, params=aug._params)).all()
        tensor(True)

    """

    def __init__(
        self,
        center_x: torch.Tensor,
        center_y: torch.Tensor,
        gamma: torch.Tensor,
        same_on_batch: bool = False,
        p: float = 0.5,
        keepdim: bool = False,
    ) -> None:
        super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
        self._check_tensor(center_x)
        self._check_tensor(center_y)
        self._check_tensor(gamma)
        self._param_generator = rg.PlainUniformGenerator(
            (center_x[:, None], "center_x", None, None),
            (center_y[:, None], "center_y", None, None),
            (gamma[:, None], "gamma", None, None),
        )

    def _check_tensor(self, data: torch.Tensor) -> None:
        if not isinstance(data, torch.Tensor):
            raise TypeError(f"Invalid input type. Expected torch.Tensor - got: {type(data)}")

        if len(data.shape) != 1 and data.shape[0] != 2:
            raise ValueError(f"torch.Tensor must be of shape (2,). Got: {data.shape}.")

    def apply_transform(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        # A half image is warped in float32: a half-precision sampling field is off by half a pixel or more at 256 px.
        out_dtype = input.dtype
        if _samples_half_in_float32(input):
            input = input.float()
        # create the initial sampling fields
        B, _, H, W = input.shape
        # A float64 image gets a float64 grid; every other dtype keeps the default-dtype grid it had before.
        grid_dtype = torch.float64 if input.dtype == torch.float64 else None
        grid = create_meshgrid(H, W, normalized_coordinates=True, dtype=grid_dtype)
        field_x = _to_device_nonblocking(grid[..., 0], input.device, input.dtype)  # 1xHxW
        field_y = _to_device_nonblocking(grid[..., 1], input.device, input.dtype)  # 1xHxW
        # vectorize the random parameters
        center_x = _to_device_nonblocking(params["center_x"].view(B, 1, 1), input.device, input.dtype)
        center_y = _to_device_nonblocking(params["center_y"].view(B, 1, 1), input.device, input.dtype)
        gamma = _to_device_nonblocking(params["gamma"].view(B, 1, 1), input.device, input.dtype)
        # compute and apply the distances respect to the camera optical center
        distance = euclidean_distance(
            torch.stack((center_x, center_y), dim=-1), torch.stack((field_x, field_y), dim=-1)
        )
        field_x = field_x + field_x * distance**gamma  # BxHxw
        field_y = field_y + field_y * distance**gamma  # BxHxW
        return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True).to(out_dtype)

    def apply_transform_mask(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Reject mask inputs, which this augmentation does not support."""
        raise NotImplementedError(
            f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."
        )

    def apply_non_transform_mask(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        """Reject mask inputs even when the transformation is not applied."""
        raise NotImplementedError(
            f"{type(self).__name__} does not support mask inputs. See https://github.com/kornia/kornia/issues/4420."
        )
