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

import torch
from torch.distributions import Uniform

from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.core.utils import _extract_device_dtype, _to_device_nonblocking
from kornia.geometry.bbox import bbox_generator

__all__ = ["MosaicGenerator"]


class MosaicGenerator(RandomGeneratorBase):
    r"""Generate the tile order and crop boxes of a mosaic for a batch of inputs.

    See the Convention block on :class:`~kornia.augmentation.RandomMosaic`.

    Args:
        output_size: the output ``(height, width)`` after mosaicing.
        mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
            each output will mix 4 images in a 2x2 grid.
        start_ratio_range: the ``(low, high)`` range from which both top-left crop ratios ``(x / W, y / H)``
            are drawn.

    Returns:
        A dict of parameters to be passed for transformation.
            - permutation (torch.Tensor): per-sample tile order with a shape of (B, N), where N is the number
              of mosaic images.
            - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
            - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
            - batch_shapes (torch.Tensor): image shapes in the batch with a shape of (B, 3).

    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,
        output_size: Optional[Tuple[int, int]] = None,
        mosaic_grid: Tuple[int, int] = (2, 2),
        start_ratio_range: Tuple[float, float] = (0.3, 0.7),
    ) -> None:
        super().__init__()
        self.output_size = output_size
        self.mosaic_grid = mosaic_grid
        self.start_ratio_range = start_ratio_range

    def __repr__(self) -> str:
        return (
            f"output_size={self.output_size}, mosaic_grid={self.mosaic_grid}, "
            f"start_ratio_range={self.start_ratio_range}"
        )

    def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
        self.start_ratio_range_sampler = Uniform(
            torch.tensor(self.start_ratio_range[0], device=device, dtype=dtype),
            torch.tensor(self.start_ratio_range[1], device=device, dtype=dtype),
            validate_args=False,
        )

    def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
        batch_size = batch_shape[0]
        input_sizes = (batch_shape[-2], batch_shape[-1])
        output_size = input_sizes if self.output_size is None else self.output_size

        _common_param_check(batch_size, same_on_batch)
        _device, _dtype = _extract_device_dtype([self.mosaic_grid])

        perm_times = self.mosaic_grid[0] * self.mosaic_grid[1]
        # Generate mosiac order in one shot
        rand_ids = torch.randperm(batch_size * (perm_times - 1), device=_device) % batch_size
        mosiac_ids = (
            torch.cat([torch.arange(0, batch_size, device=_device), rand_ids])
            .reshape(perm_times, batch_size)
            .permute(1, 0)
        )

        start_corner_factor = _to_device_nonblocking(
            _adapted_rsampling((batch_size, 2), self.start_ratio_range_sampler, same_on_batch=False), _device, _dtype
        )
        # Slice-mode crops cast the start to long (``crop_by_indices``), so a fractional start would
        # translate boxes by a sub-pixel amount the image crop never applies. Floor the start here so
        # the image and the boxes share the same integer coordinates.
        start_corner_x = torch.floor(start_corner_factor[:, 0] * batch_shape[-1])
        start_corner_y = torch.floor(start_corner_factor[:, 1] * batch_shape[-2])
        crop_src = bbox_generator(
            start_corner_x,
            start_corner_y,
            start_corner_x.clone().fill_(output_size[1]),
            start_corner_y.clone().fill_(output_size[0]),
        )
        crop_dst = _constant_tensor(
            [
                [
                    [0, 0],
                    [output_size[1] - 1, 0],
                    [output_size[1] - 1, output_size[0] - 1],
                    [0, output_size[0] - 1],
                ]
            ],
            device=_device,
            dtype=_dtype,
        ).repeat(batch_size, 1, 1)
        # NOTE: In case we support a list of torch.Tensor images later. For a better consistency.
        # B x 3

        batch_shapes: torch.Tensor
        if batch_size == 0:
            batch_shapes = torch.zeros([0, 3], device=_device, dtype=torch.long)
        else:
            batch_shapes = _constant_tensor(batch_shape[1:], device=_device, dtype=torch.long).repeat(batch_size, 1)
        return {
            "permutation": mosiac_ids.to(device=_device, dtype=torch.long),
            "src": crop_src,
            "dst": crop_dst,
            "batch_shapes": batch_shapes,
        }
