# ==========================================================================
#
#   Copyright NumFOCUS
#
#   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.txt
#
#   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.
#
# ==========================================================================*/

import sys
import unittest
import datetime as dt

import itk
import numpy as np


class TestNumpyITKMemoryviewInterface(unittest.TestCase):
    """This tests numpy array <-> ITK Scalar Image conversion."""

    def setUp(self):
        pass

    def test_NDArrayITKBase_pickle(self):
        """
        Test the serialization of itk.NDArrayITKBase
        """
        Dimension = 3
        ScalarImageType = itk.Image[itk.UC, Dimension]
        RegionType = itk.ImageRegion[Dimension]

        region = RegionType()
        region.SetSize(0, 6)
        region.SetSize(1, 6)
        region.SetSize(2, 6)

        scalarImage = ScalarImageType.New()
        scalarImage.SetRegions(region)
        scalarImage.Allocate(True)
        scalarImage.SetPixel([0, 0, 0], 5)
        scalarImage.SetPixel([0, 0, 1], 3)
        scalarImage.SetPixel([5, 5, 5], 8)
        ndarray_itk_base = itk.array_view_from_image(scalarImage)

        import pickle

        ## test serialization of itk ndarrary itk base
        pickled = pickle.dumps(ndarray_itk_base)
        reloaded = pickle.loads(pickled)
        equal = (reloaded == ndarray_itk_base).all()
        assert equal, "Different results before and after pickle"

        try:
            import dask
            from distributed.protocol.serialize import dask_dumps, dask_loads
        except ImportError:
            pass
        else:
            header, frames = dask_dumps(ndarray_itk_base)
            recon_obj = dask_loads(header, frames)
            equal = (recon_obj == ndarray_itk_base).all()
            assert equal, "Different results before and after pickle"

    def test_NumPyBridge_itkScalarImage(self):
        "Try to convert all pixel types to NumPy array view"

        Dimension = 3
        ScalarImageType = itk.Image[itk.UC, Dimension]
        RegionType = itk.ImageRegion[Dimension]

        region = RegionType()
        region.SetSize(0, 30)
        region.SetSize(1, 20)
        region.SetSize(2, 10)

        scalarImage = ScalarImageType.New()
        scalarImage.SetRegions(region)
        scalarImage.Allocate()

        scalarndarr = itk.PyBuffer[ScalarImageType].GetArrayViewFromImage(scalarImage)
        self.assertTrue(hasattr(scalarndarr, "itk_base"))
        self.assertTrue(scalarndarr.itk_base, scalarImage)
        self.assertTrue(isinstance(scalarndarr, np.ndarray))
        convertedscalarImage = itk.PyBuffer[ScalarImageType].GetImageViewFromArray(
            scalarndarr