from dqc_wrapper.test02_spatial_completeness import SpatialCompletenessTest
from dqc_wrapper.unit_tests.conftest import dirs
import xarray as xr
from pathlib import Path
import numpy as np

def test_missing_values():
    test = SpatialCompletenessTest([dirs.nc_file], 'tas', 'nc', 0,
                                   dirs.mask_file, 'tas')
    mv, uv, _= test.missing_values(dirs.nc_file)
    assert mv == 0 and uv == 800 # 160 uv * 5 time steps = 800
    # Without mask
    test = SpatialCompletenessTest([dirs.nc_file], 'tas', 'nc', 0, "", 'tas')
    mv, uv, _ = test.missing_values(dirs.nc_file)
    assert mv == 0 and uv == 0


def test_check_spatial_completeness():
    test = SpatialCompletenessTest([dirs.nc_file], 'tas', 'nc', 0,
                                   dirs.mask_file, 'tas')
    # 1: Error because of unnecesary values
    res, msg = test.check_spatial_completeness()
    assert res == "err"
    # 2: Without mask
    test = SpatialCompletenessTest([dirs.nc_file], 'tas', 'nc', 0,
                                   "", 'tas')
    res, msg = test.check_spatial_completeness()
    assert res == "ok"

    # 3: With mask: masking nc so the test passes
    test = SpatialCompletenessTest([dirs.nc_file], 'tas', 'nc', 0,
                                   dirs.mask_file, 'tas')
    ds = xr.open_dataset(dirs.nc_file)
    mask = xr.open_dataset(dirs.mask_file)
    ds = ds.where(~mask)
    fake_file = Path(dirs.test_dir, "spatial_completeness.nc")
    ds.to_netcdf(fake_file)
    ds.close()
    test = SpatialCompletenessTest([str(fake_file)], 'tas', 'nc', 0,
                                   dirs.mask_file, 'tas')
    res, msg = test.check_spatial_completeness()
    assert res == "ok"

    # 4: Error because of missing values
    ds['tas'][0, 0, 0] = np.nan
    ds.to_netcdf(fake_file)
    test = SpatialCompletenessTest([str(fake_file)], 'tas', 'nc', 0,
                                   dirs.mask_file, 'tas')
    res, msg = test.check_spatial_completeness()
    assert res == "err"
    #Deleting nc
    fake_file.unlink()
