import pytest
from bids.layout import BIDSLayout
from bids.layout.layout import MetadataIndex
from os.path import join, abspath, sep
from bids.tests import get_test_data_path


# Fixture uses in the rest of the tests
@pytest.fixture(scope='module')
def layout():
    data_dir = join(get_test_data_path(), '7t_trt')
    return BIDSLayout(data_dir)


@pytest.fixture(scope='module')
def index(layout):
    return MetadataIndex(layout)


def test_index_inits(index):
    assert hasattr(index, 'key_index')
    assert hasattr(index, 'file_index')
    assert index.key_index
    assert index.file_index
    keys = {'EchoTime2', 'EchoTime1', 'IntendedFor', 'CogAtlasID', 'EchoTime',
            'EffectiveEchoSpacing', 'PhaseEncodingDirection', 'RepetitionTime',
            'SliceEncodingDirection', 'SliceTiming', 'TaskName', 'StartTime',
            'SamplingFrequency', 'Columns'}
    assert keys == set(index.key_index.keys())
    targ = 'sub-04/ses-1/func/sub-04_ses-1_task-rest_acq-fullbrain_run-1_bold.nii.gz'
    targ = targ.split('/')
    targ = join(get_test_data_path(), '7t_trt', *targ)
    assert targ in index.file_index
    assert index.file_index[targ]['EchoTime'] == 0.017


def test_search_with_no_args(index):
    with pytest.raises(ValueError) as exc:
        index.search()
    assert str(exc.value).startswith("At least one field")


def test_search_with_missing_keys(index):
    # Searching with invalid keys should return nothing
    res = index.search(keys_exist=['EchoTiming', 'Echolalia', 'EchoOneNiner'])
    assert res == []
    assert index.search(EchoTiming='eleventy') == []


def test_search_with_no_matching_value(index):
    results = index.search(EchoTime=0.017)
    assert results


def test_search_with_file_constraints(index, layout):
    files = layout.get(subject='03', return_type='file')
    results = index.search(EchoTime=0.017, files=files)
    assert len(results) == 4


def test_index_builds_from_layout():
    data_dir = join(get_test_data_path(), '7t_trt')
    layout = BIDSLayout(data_dir, index_metadata=False)
    assert layout.metadata_index is None
    layout = BIDSLayout(data_dir, index_metadata=True)
    assert isinstance(layout.metadata_index, MetadataIndex)

@@ -408,29 +408,29 @@
 urn 
-M
+layout.m
 etadata
-I
+_i
 ndex
-(layout)
 %0A%0A%0Ad
@@ -543,24 +543,28 @@
 %0A    assert 
+not 
 index.key_in
@@ -570,32 +570,36 @@
 ndex%0A    assert 
+not 
 index.file_index
@@ -594,24 +594,619 @@
 x.file_index
+%0A%0Adef test_get_metadata_caches_in_index(layout):%0A    targ = 'sub-04/ses-1/func/sub-04_ses-1_task-rest_acq-fullbrain_run-1_bold.nii.gz'%0A    targ = targ.split('/')%0A    targ = join(get_test_data_path(), '7t_trt', *targ)%0A    mdi = layout.metadata_index%0A    assert not mdi.file_index%0A    md = layout.get_metadata(targ)%0A    assert targ in mdi.file_index%0A    assert len(mdi.file_index) == 1%0A    assert 'CogAtlasID' in mdi.key_index%0A    assert 'RepetitionTime' in mdi.key_index%0A%0Adef test_searching_without_file_list_indexes_everything(index):%0A    res = index.search(nonexistent_key=2)%0A    assert not res
 %0A    keys = 
@@ -1269,28 +1269,24 @@
 'EchoTime',%0A
-    
         'Eff
@@ -1357,20 +1357,16 @@
         
-  
-  
 'SliceEn
@@ -1431,20 +1431,16 @@
         
-    
 'Samplin
@@ -1461,16 +1461,39 @@
 Columns'
+, 'BIDSVersion', 'Name'
 %7D%0A    as
@@ -1793,17 +1793,16 @@
  0.017%0A%0A
-%0A
 def test
@@ -2521,307 +2521,4 @@
 = 4%0A
-%0A%0Adef test_index_builds_from_layout():%0A    data_dir = join(get_test_data_path(), '7t_trt')%0A    layout = BIDSLayout(data_dir, index_metadata=False)%0A    assert layout.metadata_index is None%0A    layout = BIDSLayout(data_dir, index_metadata=True)%0A    assert isinstance(layout.metadata_index, MetadataIndex)%0A

fix metadata indexing tests