from src.data_handling.bootstraps import BootStraps

import pytest
import os

import numpy as np


class TestBootstraps:

    @pytest.fixture
    def path(self):
        path = os.path.join(os.path.dirname(__file__), "data")
        if not os.path.exists(path):
            os.makedirs(path)
        return path

    @pytest.fixture
    def boot_no_init(self, path):
        obj = object.__new__(BootStraps)
        super(BootStraps, obj).__init__()
        obj.number_bootstraps = 50
        obj.bootstrap_path = path
        return obj

    def test_valid_bootstrap_file(self, path, boot_no_init):
        station = "TESTSTATION"
        variables = "var1_var2_var3"
        window = 5
        # empty case
        assert len(os.listdir(path)) == 0
        assert boot_no_init.valid_bootstrap_file(station, variables, window) == (False, 50)
        # different cases, where files with bigger range are existing
        os.mknod(os.path.join(path, f"{station}_{variables}_hist5_nboots50_shuffled.dat"))
        assert boot_no_init.valid_bootstrap_file(station, variables, window) == (True, None)
        os.mknod(os.path.join(path, f"{station}_{variables}_hist5_nboots100_shuffled.dat"))
        assert boot_no_init.valid_bootstrap_file(station, variables, window) == (True, None)
        os.mknod(os.path.join(path, f"{station}_{variables}_hist10_nboots50_shuffled.dat"))
        os.mknod(os.path.join(path, f"{station}1_{variables}_hist10_nboots50_shuffled.dat"))
        assert boot_no_init.valid_bootstrap_file(station, variables, window) == (True, None)
        #  need to reload data and therefore remove not fitting files for this station
        assert boot_no_init.valid_bootstrap_file(station, variables, 20) == (False, 100)
        assert len(os.listdir(path)) == 1
        # reload because expanded boot number
        os.mknod(os.path.join(path, f"{station}_{variables}_hist5_nboots50_shuffled.dat"))
        boot_no_init.number_bootstraps = 60
        assert boot_no_init.valid_bootstrap_file(station, variables, window) == (False, 60)
        assert len(os.listdir(path)) == 1
        # reload because of expanded window size, but use maximum boot number from file names
        os.mknod(os.path.join(path, f"{station}_{variables}_hist5_nboots60_shuffled.dat"))
        boot_no_init.number_bootstraps = 50
        assert boot_no_init.valid_bootstrap_file(station, variables, 20) == (False, 60)

    def test_shuffle_single_variale(self, boot_no_init):
        data = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
        res = boot_no_init.shuffle_single_variable(data)
        assert res.shape == data.shape
        assert res.max() == data.max()
        assert res.min() == data.min()
        assert set(np.unique(res)).issubset({1, 2, 3})

    def test_create_shuffled_data(self):
        pass