# 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 Dict, Tuple, Union

import torch

from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import (
    _adapted_rsampling,
    _check_positive_int_or_traced,
    _common_param_check,
    _joint_range_check,
    _shear_bound,
)
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.core.utils import _extract_device_dtype, _to_device_nonblocking

__all__ = ["ShearGenerator"]


class ShearGenerator(RandomGeneratorBase):
    r"""Get parameters for ``shear`` for a random shear transform.

    Args:
        shear: Range of degrees to select from.
            If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
            If (a, b), a shear parallel to the x axis in the range (a, b) will be applied.
            If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
            will be applied. Will not apply shear by default.
            If torch.Tensor, shear is a 2x2 torch.Tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
            y-axis shear in
            (shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.

    Returns:
        A dict of parameters to be passed for transformation.
            - shear_x (torch.Tensor): element-wise x-axis shears with a shape of (B,).
            - shear_y (torch.Tensor): element-wise y-axis shears with a shape of (B,).

    Note:
        The generated random numbers are not reproducible across different devices and dtypes. By default,
        the parameters will be generated on CPU in float32. This can be changed by calling
        ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.

    """

    def __init__(
        self, shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float]]
    ) -> None:
        super().__init__()
        self.shear = shear

    def __repr__(self) -> str:
        return f"shear={self.shear}"

    def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
        _shear = _shear_bound(self.shear, device, dtype)

        _joint_range_check(_shear[0], "shear")
        _joint_range_check(_shear[1], "shear")
        self.shear_x = _shear[0].clone()
        self.shear_y = _shear[1].clone()

        shear_x_sampler = UniformDistribution(_shear[0][0], _shear[0][1], validate_args=False)
        shear_y_sampler = UniformDistribution(_shear[1][0], _shear[1][1], validate_args=False)

        self.shear_x_sampler = shear_x_sampler
        self.shear_y_sampler = shear_y_sampler

    def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
        batch_size = batch_shape[0]
        height = batch_shape[-2]
        width = batch_shape[-1]

        _device, _dtype = _extract_device_dtype([self.shear])
        _common_param_check(batch_size, same_on_batch)
        _check_positive_int_or_traced(width, "width")
        _check_positive_int_or_traced(height, "height")

        center: torch.Tensor = _constant_tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
        center = center.expand(batch_size, -1)

        sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)
        sy = _adapted_rsampling((batch_size,), self.shear_y_sampler, same_on_batch)
        sx = _to_device_nonblocking(sx, _device, _dtype)
        sy = _to_device_nonblocking(sy, _device, _dtype)

        return {"center": center, "shear_x": sx, "shear_y": sy}
