# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Test the second level model.
"""
from __future__ import with_statement

import os

import numpy as np
import pandas as pd
import warnings

from nibabel import (load,
                     Nifti1Image,
                     )
from nibabel.tmpdirs import InTemporaryDirectory
from nilearn.image import concat_imgs
from nose.tools import (assert_true,
                        assert_equal,
                        assert_raises,
                        )
from numpy.testing import (assert_almost_equal,
                           assert_array_equal,
                           )

from nistats.first_level_model import (FirstLevelModel,
                                       run_glm,
                                       )
from nistats.second_level_model import SecondLevelModel
from nistats._utils.testing import _write_fake_fmri_data

# This directory path
BASEDIR = os.path.dirname(os.path.abspath(__file__))
FUNCFILE = os.path.join(BASEDIR, 'functional.nii.gz')


def test_high_level_glm_with_paths():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1),)
        mask, FUNCFILE, _ = _write_fake_fmri_data(shapes)
        FUNCFILE = FUNCFILE[0]
        func_img = load(FUNCFILE)
        # Ordinary Least Squares case
        model = SecondLevelModel(mask_img=mask)
        # asking for contrast before model fit gives error
        assert_raises(ValueError, model.compute_contrast, [])
        # fit model
        Y = [func_img] * 4
        X = pd.DataFrame([[1]] * 4, columns=['intercept'])
        model = model.fit(Y, design_matrix=X)
        c1 = np.eye(len(model.design_matrix_.columns))[0]
        z_image = model.compute_contrast(c1, output_type='z_score')
        assert_true(isinstance(z_image, Nifti1Image))
        assert_array_equal(z_image.affine, load(mask).affine)
        # Delete objects attached to files to avoid WindowsError when deleting
        # temporary directory (in Windows)
        del Y, FUNCFILE, func_img, model


def test_fmri_inputs():
    # Test processing of FMRI inputs
    with InTemporaryDirectory():
        # prepare fake data
        p, q = 80, 10
        X = np.random.randn(p, q)
        shapes = ((7, 8, 9, 10),)
        mask, FUNCFILE, _ = _write_fake_fmri_data(shapes)
        FUNCFILE = FUNCFILE[0]
        func_img = load(FUNCFILE)
        T = func_img.shape[-1]