# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "05/04/2019"


import os
import shutil
import tempfile
import unittest
import numpy
from tomwer.core.utils.scanutils import MockEDF, MockHDF5
from tomwer.core.process.reconstruction.darkref.params import DKRFRP, Method as cMethod
from tomwer.core.scan.scanbase import TomwerScanBase
from ..reconstruction.darkref.darkrefs import DarkRefs
from ..reconstruction.darkref.darkrefscopy import DarkRefsCopy
from tomwer.test.utils import UtilsTest
from tomwer.core.scan.hdf5scan import HDF5TomoScan
from silx.io.utils import get_data


class TestDarkRefIO(unittest.TestCase):
    """Test inputs and outputs types of the handler functions"""

    def setUp(self):
        self.scan_folder = tempfile.mkdtemp()

        self.scan_edf = MockEDF.mockScan(scanID=self.scan_folder,
                                         nRadio=10,
                                         nRecons=1,
                                         nPagRecons=4,
                                         dim=10)
        self.mock_hdf5 = MockHDF5(scan_path=self.scan_folder, n_proj=10,
                                  n_pag_recons=0)
        self.scan_hdf5 = self.mock_hdf5.scan

        self.recons_params = DKRFRP()
        self.dkrf_process = DarkRefs(self.recons_params)

    def tearDown(self):
        shutil.rmtree(self.scan_folder)

    def testInputOutput(self):
        for scan, scan_type in zip((self.scan_edf, self.scan_hdf5), ('edf scan', 'hdf5 scan')):
            for input_type in (dict, TomwerScanBase):
                for _input in DarkRefs.inputs:
                    for return_dict in (True, False):
                        with self.subTest(handler=_input.handler,
                                          return_dict=return_dict,
                                          input_type=input_type,
                                          scan_type=scan_type):
                            input_obj = scan
                            if input_obj is dict:
                                input_obj = input_obj.to_dict()
                            self.dkrf_process._set_return_dict(return_dict)
                            out = getattr(self.dkrf_process, _input.handler)(input_obj)
                            if return_dict:
                                self.assertTrue(isinstance(out, dict))
                            else:
                                self.assertTrue(isinstance(out, TomwerScanBase))


class TestDarkRefCopyIO(unittest.TestCase):
    """Test inputs and outputs types of the handler functions"""

    def setUp(self):
        self.scan_folder = tempfile.mkdtemp()

        self.scan_edf = MockEDF.mockScan(scanID=self.scan_folder,
                                         nRadio=10,
                                         nRecons=1,
                                         nPagRecons=4,
                                         dim=10)
        self.scan_hdf5 = MockHDF5(scan_path=self.scan_folder, n_proj=10,
                                  n_pag_recons=0).scan
        self.recons_params = DKRFRP()
        self.dkrf_process = DarkRefsCopy(self.recons_params)

    def tearDown(self):
        shutil.rmtree(self.scan_folder)

    def testInputOutput(self):
        for scan, scan_type in zip((self.scan_edf, self.scan_hdf5), ('edf scan', 'hdf5 scan')):
            for input_type in (dict, TomwerScanBase):
                for _input in DarkRefsCopy.inputs:
                    for return_dict in (True, False):
                        with self.subTest(handler=_input.handler,
                                          return_dict=return_dict,
                                          input_type=input_type,
                                          scan_type=scan_type):
                            input_obj = scan
                            if input_obj is dict:
                                input_obj = input_obj.to_dict()
                            self.dkrf_process._set_return_dict(return_dict)
                            out = getattr(self.dkrf_process, _input.handler)(input_obj)
                            if return_dict:
                                self.assertTrue(isinstance(out, dict))
                            else:
                                self.assertTrue(isinstance(out, TomwerScanBase))


class TestDarkRefNx(unittest.TestCase):
    """
    Test dark ref is correctly processing with h5 refs
    """
    def setUp(self) -> None:
        dataset_name = 'frm_edftomomill_twoentries.nx'
        self.scan_folder = tempfile.mkdtemp()
        self._file_path = os.path.join(self.scan_folder, dataset_name)
        shutil.copyfile(src=UtilsTest.getH5Dataset(folderID=dataset_name),
                        dst=self._file_path)
        self.scan = HDF5TomoScan(scan=self._file_path, entry='entry0000')
        self.recons_params = DKRFRP()
        self.process = DarkRefs(reconsparams=self.recons_params)
        self.assertFalse(os.path.exists(self.scan.process_file))

    def tearDown(self) -> None:
        shutil.rmtree(self.scan_folder)

    def testDark(self):
        darks = self.scan.darks
        self.assertEqual(len(darks), 1)
        dark_data = get_data(list(darks.values())[0])

        for method in (cMethod.average, cMethod.median):
            with self.subTest(method=method):
                self.recons_params.dark_calc_method = method
                self.recons_params.ref_calc_method = cMethod.none
                self.process.process(scan=self.scan)
                self.assertTrue(os.path.exists(self.scan.process_file))
                darks = DarkRefs.get_darks_frm_process_file(self.scan.process_file,
                                                            entry=self.scan.entry)
                self.assertEqual(len(darks), 1)
                self.assertTrue(numpy.allclose(darks[0], dark_data))
                flats = DarkRefs.get_flats_frm_process_file(self.scan.process_file,
                                                            entry=self.scan.entry)
                self.assertEqual(len(flats), 0)

    def testFlat(self):
        flats = self.scan.flats
        self.assertEqual(len(flats), 42)
        url_flat_serie_1 = [flats[index] for index in range(1, 22)]
        url_flat_serie_2 = [flats[index] for index in range(1521, 1542)]
        assert len(url_flat_serie_1) == 21
        assert len(url_flat_serie_2) == 21
        data_flat_serie_1 = [get_data(url) for url in url_flat_serie_1]
        data_flat_serie_2 = [get_data(url) for url in url_flat_serie_2]

        for method in (cMethod.average, cMethod.median):
            with self.subTest(method=method):
                if method is cMethod.median:
                    expected_res_s1 = numpy.median(data_flat_serie_1, axis=0)
                    expected_res_s2 = numpy.median(data_flat_serie_2, axis=0)
                else:
                    expected_res_s1 = numpy.mean(data_flat_serie_1, axis=0)
                    expected_res_s2 = numpy.mean(data_flat_serie_2, axis=0)

                self.recons_params.dark_calc_method = cMethod.none
                self.recons_params.ref_calc_method = method
                self.process.process(scan=self.scan)
                self.assertTrue(os.path.exists(self.scan.process_file))
                darks = DarkRefs.get_darks_frm_process_file(self.scan.process_file,
                                                            entry=self.scan.entry)
                self.assertEqual(len(darks), 0)
                flats = DarkRefs.get_flats_frm_process_file(self.scan.process_file,
                                                            entry=self.scan.entry)
                self.assertEqual(len(flats), 2)
                self.assertTrue(1 in flats)
                self.assertTrue(1521 in flats)
                self.assertTrue(numpy.allclose(flats[1], expected_res_s1))
                self.assertTrue(numpy.allclose(flats[1521], expected_res_s2))

    def testDarkAndFlat(self):
        flats = self.scan.flats
        self.assertEqual(len(flats), 42)
        url_flat_serie_1 = [flats[index] for index in range(1, 22)]
        url_flat_serie_2 = [flats[index] for index in range(1521, 1542)]
        assert len(url_flat_serie_1) == 21
        assert len(url_flat_serie_2) == 21
        data_flat_serie_1 = [get_data(url) for url in url_flat_serie_1]
        data_flat_serie_2 = [get_data(url) for url in url_flat_serie_2]

        self.recons_params.dark_calc_method = cMethod.average
        self.recons_params.ref_calc_method = cMethod.median
        darks = self.scan.darks
        self.assertEqual(len(darks), 1)
        dark_data = get_data(list(darks.values())[0])

        expected_flats_s1 = numpy.median(data_flat_serie_1, axis=0)
        expected_flats_s2 = numpy.median(data_flat_serie_2, axis=0)

        self.process.process(scan=self.scan)
        self.assertTrue(os.path.exists(self.scan.process_file))
        darks = DarkRefs.get_darks_frm_process_file(self.scan.process_file,
                                                    entry=self.scan.entry)
        self.assertEqual(len(darks), 1)
        flats = DarkRefs.get_flats_frm_process_file(self.scan.process_file,
                                                    entry=self.scan.entry)
        self.assertEqual(len(flats), 2)
        self.assertTrue(0 in darks)
        self.assertTrue(1 in flats)
        self.assertTrue(1521 in flats)
        self.assertTrue(numpy.allclose(flats[1], expected_flats_s1))
        self.assertTrue(numpy.allclose(flats[1521], expected_flats_s2))
        self.assertTrue(numpy.allclose(darks[0], dark_data))


class TestDarkRefCopyNx(unittest.TestCase):
    """
    Test dark ref is correctly processing with h5 refs
    """
    def setUp(self) -> None:
        dataset_name = 'frm_edftomomill_twoentries.nx'
        self.scan_folder = tempfile.mkdtemp()
        self._file_path = os.path.join(self.scan_folder, dataset_name)
        shutil.copyfile(src=UtilsTest.getH5Dataset(folderID=dataset_name),
                        dst=self._file_path)
        self.scan_with_ref = HDF5TomoScan(scan=self._file_path, entry='entry0000')
        self.recons_params = DKRFRP()
        self.dkref_process = DarkRefs(reconsparams=self.recons_params)
        self.copy_process = DarkRefsCopy(reconsparams=self.recons_params)
        self.assertFalse(os.path.exists(self.scan_with_ref.process_file))

        mock = MockHDF5(scan_path=self.scan_folder, n_proj=10, n_ini_proj=2,
                        n_pag_recons=0, create_ini_dark=False,
                        create_ini_ref=False)
        self.scan_without_ref = mock.scan
        # make sure no ref and no dark registered
        assert len(self.scan_without_ref.darks) == 0
        assert len(self.scan_with_ref.darks) > 0
        assert len(self.scan_without_ref.flats) == 0
        assert len(self.scan_with_ref.flats) > 0
        assert self.scan_without_ref.normed_flats is None
        assert self.scan_with_ref.normed_flats is None
        assert self.scan_without_ref.normed_darks is None
        assert self.scan_with_ref.normed_darks is None

    def tearDown(self) -> None:
        shutil.rmtree(self.scan_folder)

    def testCopyAuto(self):
        """Test copy in mode auto"""
        self.copy_process.set_mode_auto(True)
        self.copy_process.process(scan=self.scan_with_ref)
        self.assertFalse(self.scan_with_ref.normed_flats is None)
        self.assertEqual(len(self.scan_with_ref.normed_flats), 2)
        self.assertFalse(self.scan_with_ref.normed_darks is None)
        self.assertEqual(len(self.scan_with_ref.normed_darks), 1)
        self.copy_process.process(scan=self.scan_without_ref)
        self.assertFalse(self.scan_without_ref.normed_flats is None)
        self.assertEqual(len(self.scan_without_ref.normed_flats), 2)
        self.assertFalse(self.scan_without_ref.normed_darks is None)
        self.assertEqual(len(self.scan_without_ref.normed_darks), 1)
        # TODO: try to read them from tomwer_processes.h5
        darks = DarkRefs.get_darks_frm_process_file(self.scan_with_ref.process_file)
        self.assertEqual(len(darks), 1)
        flats = DarkRefs.get_flats_frm_process_file(self.scan_with_ref.process_file)
        self.assertEqual(len(flats), 1)

    def testCopyManual(self):
        """Test copy un manual mode"""
        self.copy_process.set_mode_auto(False)


def suite():
    test_suite = unittest.TestSuite()
    for ui in (TestDarkRefIO, TestDarkRefCopyIO):
        test_suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ui))
    return test_suite

