from dqc_wrapper.test06_valid_ranges import ValidRangesTest
from dqc_wrapper.unit_tests.conftest import dirs
import xarray as xr
import numpy as np
import pandas as pd


def test_get_basic_stats():
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '', 0, '', dirs.test_dir, '', 'tas')
    ds = xr.open_dataset(dirs.nc_file)
    # random values between 10 and 25
    Min, Max, Mean, Std, Med, q1, q3, IQD, skew = test.get_basic_stats(ds['tas'].data)
    assert Min >= 10
    assert Max <= 25
    assert Mean >= Min and Mean <= Max
    assert Std > 0


def test_load_datafile():
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '',  0, '', dirs.test_dir, '', 'tas')
    ds, arr, _ = test.load_datafile(dirs.nc_file)
    assert ds
    assert len(arr) == 5*320*160


def test_get_hist_hadley():
    df_hist = pd.DataFrame(index=['N_polar'], columns=np.arange(15))
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '', 0, '', dirs.test_dir, '', 'tas')
    ds = xr.open_dataset(dirs.nc_file)
    test.get_hist_hadley(df_hist, np.arange(10, 26), ds, 0, 60, 90, 'N_polar',
                         'lat')
    assert df_hist.shape == (1, 15)


def test_get_bins_init():
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '', 0, '', dirs.test_dir, '', 'tas')
    hist, _ = test.get_bins_init(dirs.nc_file)
    assert len(hist) == 2001


def test_get_stats_files():
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '',  0, '',  dirs.test_dir, '', 'tas')
    stats, hist = test.get_stats_files()
    assert stats == dirs.stats_csv
    assert hist == dirs.hist_csv

def test_check_valid_ranges():
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', '', '', 0, '', dirs.test_dir, '', 'tas')
    res, msg = test.check_valid_ranges()
    assert res == "ok"
    # Min and max outside range
    test = ValidRangesTest(dirs.log_dir, 'testname.ini', [dirs.nc_file],
                           'tas', 100, 200, 0, '', dirs.test_dir, '', 'tas')
    res, msg = test.check_valid_ranges()
    assert res == "err"
