# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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 __future__ import absolute_import, division

import numpy as np
from PIL import Image
from nnabla.logger import logger

from .common import _imread_before, _imread_after, _imsave_before, _imresize_before, _imresize_after
from .image_utils_backend import ImageUtilsBackend


class PilBackend(ImageUtilsBackend):
    _interpolations_map = {
        "nearest": Image.NEAREST,
        "bilinear": Image.BILINEAR,
        "bicubic": Image.BICUBIC,
    }

    def __init__(self):
        ImageUtilsBackend.__init__(self)
        if hasattr(Image, "HAMMING"):  # version >3.4.0
            self._interpolations_map["hamming"] = Image.HAMMING

        if hasattr(Image, "BOX"):  # version >3.4.0
            self._interpolations_map["box"] = Image.BOX

        if hasattr(Image, "LANCZOS"):  # version >1.1.3
            self._interpolations_map["lanczos"] = Image.LANCZOS

    @staticmethod
    def convert_pil(pil_image, grayscale, num_channels, return_palette_indices):
        if pil_image.mode == "I":
            raise ValueError(
                "Input img type seems int32. Currently we don`t support int32 image in pillow backend.")

        # Note:
        #   This code block below is copied from
        #   https://github.com/scipy/scipy/blob/maintenance/1.2.x/scipy/misc/pilutil.py.
        if pil_image.mode == 'P' and not return_palette_indices:
            # Mode 'P' means there is an indexed "palette".  If we leave the mode
            # as 'P', then when we do `a = array(im)` below, `a` will be a 2-D
            # containing the indices into the palette, and not a 3-D array
            # containing the RGB or RGBA values.
            if 'transparency' in pil_image.info:
                pil_image = pil_image.convert('RGBA')
            else:
                pil_image = pil_image.convert('RGB')