import shutil
import os 
import os.path as osp
import glob as gb
import json
import numpy as np
#from six import string_types
#
from nilearn import masking as msk
from nilearn._utils import concat_niimgs
# from nilearn.image.image import _compute_mean
#
import utils._utils as ucr
import utils.setup_filenames as suf 
import argparse

DIRLAYOUT = 'directory_layout.json'
DATAPARAM = 'data_parameters.json'
ANALPARAM = 'analysis_parameters.json'

def get_params(dbase, verbose=False):
    """
    parameters:
    -----------
    dbase:  string
            base directory containing subjects directory
            and jason files
    """

    # Read json files at the base directory
    fn_layo = osp.join(dbase, DIRLAYOUT)
    fn_data = osp.join(dbase, DATAPARAM)
    fn_anal = osp.join(dbase, ANALPARAM)

    with open(fn_layo) as flayo:
        dlayo = json.load(flayo)
    with open(fn_data) as fdata:
        ddata = json.load(fdata)
    with open(fn_anal) as fanal:
        danal = json.load(fanal)

    params = {'layout': dlayo, 'data': ddata, 'analysis': danal}
    return params

def process_all(dbase, params=None, verbose=False):
    """
    parameters:
    -----------
    dbase:  string
            base directory containing subjects directory
            and jason files
    """
    if not params:
        params = get_params(dbase, verbose=verbose)
    
    dlayo = params['layout']
    ddata = params['data']

    # loop over subjects
    subj_idx = range(1,ddata['nb_sub']+1) # starts at 1, hence + 1
    subj_dirs = [osp.join(dbase, (dlayo['dir']['sub+']).format(idx)) for idx in subj_idx]
    # check all subj_dirs exists
    for sub_dir in subj_dirs:
        assert osp.isdir(sub_dir), "sub_dir"

    subjs_info = {}
    sub_curr = {}
    for sub_idx, sub_dir in enumerate(subj_dirs, 1): # start idx at 1
        sub_curr['sub_idx'] = sub_idx
        sub_curr['sub_dir'] = sub_dir
        sub_str = (dlayo['dir']['sub+']).format(sub_idx)
        subjs_info[sub_str] =  do_one_subject(sub_curr, params, verbose=verbose) 

    return subjs_info

def do_one_subject(sub_curr, params, verbose=False):
    """
    launch sessions processing for sub_curr 

    parameters:
    -----------
    sub_curr: dict 
            contains subject base directory
            contains subject index 
    params: dict
            parameters for layout, data and analysis
            
    """
    sub_idx, sub_dir = sub_curr['sub_idx'], sub_curr['sub_dir']
    nb_sess = params['data']['nb_sess']
    dlayo = params['layout']