import pathlib
import unittest

try:
    import pivtestdata as ptd
except ImportError:
    ptd = None

import pivimage

__this_dir__ = pathlib.Path(__file__).parent


class TestMetadata(unittest.TestCase):

    def setUp(self) -> None:
        if ptd is None:
            self.skipTest('pivtestdata is required for dataset-backed tests')
        pc_1B = ptd.piv_challenge.pc_1B
        sample_folder_pc_1B = pc_1B.download()
        self.filenames = sorted(sample_folder_pc_1B.glob('*.tif*'))

    def test_dict(self):
        pivimg = pivimage.PIVImage(self.filenames[0],
                                   meta={'name': 'test image'})
        self.assertIsInstance(pivimg.meta, pivimage.meta.Metadata)
        pivimg.meta.save(filename='test.json')
        filename = pivimg.meta.save()
        self.assertTrue(filename.exists())
        filename.unlink(missing_ok=True)

        no_filename_pivimg = pivimage.PIVImage(None)
        with self.assertRaises(ValueError):
            filename = no_filename_pivimg.meta.save()

        pathlib.Path('test.json').unlink(missing_ok=True)


class TestMetadataStandalone(unittest.TestCase):

    def test_metadata_add_and_yaml_save(self):
        pivimg = pivimage.PIVImage(None, meta={'name': 'test'})
        pivimg.meta.add('camera', 'pco')
        pivimg.meta.update(run_id='001')
        self.assertEqual(pivimg.meta.data['name'], 'test')
        self.assertEqual(pivimg.meta.data['camera'], 'pco')
        self.assertEqual(pivimg.meta.data['run_id'], '001')

        yaml_file = pathlib.Path('meta_test.yaml')
        saved = pivimg.meta.save(filename=yaml_file)
        self.assertEqual(saved, yaml_file)
        self.assertTrue(yaml_file.exists())
        yaml_file.unlink(missing_ok=True)
