import pytest
import preciso
import numpy 
import pandas
from pathlib import Path
import h5py
import sys
import os
import glob
import tests


@pytest.mark.parametrize("test_file", glob.glob('./tests/testFiles/*.hdf5')) #To run the test on other files, add them to [PreciSo's root]/tests/testFiles or add their path to the list generated by glob

def test_precipitation(test_file):
        '''Test if the simulation's and reference's precipitation DataFrames match'''

        TEST = tests.Tests(test_file)

        for node in TEST.REF_FILE['precipitation'].keys():
  
            node_int = int(node[5:])
            SIM = TEST.simVal.precipitation[node_int]
            REF = pandas.read_hdf(test_file, 'precipitation/'+node)
            SIM, REF = TEST.reformat(SIM, REF)
            ERR = TEST.comp_DF(SIM, REF)
            mismatches = []

            assert ERR.columns[0] == 't[s]', 'FILE {}; FormatError: In {} Both dataFrames\' first column should be temporal values'.format(os.path.split(test_file)[-1], node)

            assert ERR.iloc[0, 0] < TEST.tolerances['t[s]'], 'FILE {}; FormatError: In {} Something went wrong while formating the DataFrames; the time values mismatch'.format(os.path.split(test_file)[-1], node)
 
            for label in ERR.columns[1:]:
                assert not(TEST.match_tol(label) is None), 'FILE {}; FormatError: In {} The label {} has its tolerance undefined, or was not effectively removed during formating'.format(os.path.split(test_file)[-1], node, label)
                if ERR.loc[:, label][0] >= TEST.match_tol(label):
                    mismatches.append('ValueWarning: In {} : Mean relative error for {} is {}, which exceeds tolerance'.format(node, label, ERR.loc[:, label][0]))
            
            assert not(mismatches), 'FILE {}; '.format(os.path.split(test_file)[-1])+'\n'.join(mismatches) 
