#!/usr/bin/env python

from os.path import join as pjoin

import numpy as np
import pandas as pd


def log2tsv_rionly(log_infile,
                   tsv_outfile,
                   stimdur=1.1,
                   dropcols=('vision', 'Sitzung', 'Gechlecht', 'SubjectID', 'object_name', 'MRDB-ID',
                             'Alter', 'Rechtshaendig', 'exp_name', 'date', 'first_trigger', 'block',
                             'last_dummy_trigger', 'iti', 'ran', 'responses', 'trial_num')):
    """
    Take one log file generated by the experiment and save it as a bids-compatible events.tsv file

    Parameters
    ----------
    log_infile : str
        path to input log file (csv)
    tsv_outfile : str
        path to output tsv file
    dropcols : tuple
        columns of the input csv that are not needed and will not be kept.
    """

    # load in pandas
    df = pd.read_csv(log_infile)
    # rename columns
    df = df.rename(index=str, columns={"global_onset_time": "onset", "RT": "response_time",
                                       'trial_type': 'catch_normal', 'file_path': 'stim_file'})
    # drop bids-redundant columns
    df = df.drop(list(dropcols), axis=1)
    # create column 'trial_type'
    df['trial_type'] = ''
    for row_idx, stim_path in enumerate(df['stim_file']):
        trial_type = stim_path.split('/')[-1].replace('_ri_percept.png', '')
        df['trial_type'][row_idx] = trial_type
    df['trial_type'][df.catch_normal == 'catch'] = 'catch'
    df = df.drop(['catch_normal'], axis=1)
    # rename column 'stim_file'
    df['stim_file'] = df['stim_file'].apply(lambda x: x.replace('./Stimuli/', ''))
    # create column 'duration' with constant value
    df['duration'] = stimdur
    # replace regular NaN with string "n/a"
    df = df.replace(np.nan, 'n/a')
    # write df to destination file
    column_order = ['onset', 'duration', 'trial_type', 'response_time', 'accuracy', 'object_id', 'rotation',
                    'stim_file']
    df[column_order].to_csv(tsv_outfile, sep='\t', index=None)


def log2tsv_all(log_infile,
                tsv_outfile,
                stimdur=1.1,
                dropcols=('vision', 'Sitzung', 'Gechlecht', 'SubjectID', 'object_name', 'MRDB-ID',
                          'Alter', 'Rechtshaendig', 'exp_name', 'date', 'first_trigger', 'block',
                          'last_dummy_trigger', 'iti', 'ran', 'responses', 'trial_num')):
    df = pd.read_csv(log_infile)
    import pdb;pdb.set_trace()
    # TODO: convert one log file to events.tsv
    #  for the 3 runs with all stimuli
    return None


def convert_task_rionly(bids_dir='/home/my_data/exppsy/oliver/RIRSA/scratch/BIDS',
                        fmri_log_dir='/home/my_data/exppsy/oliver/RIRSA/raw/my_data/fmri_logs',
                        n_subs=6):
    """
    Iterate through all subjects, sessions, and runs to convert log files to bids-events for our ri_only task
    (i.e. runs 1-4 in both sessions)
    Parameters
    ----------
    bids_dir : str
        path to bids dataset base directory
    fmri_log_dir : str
        path to base directory containing the fmri log files as generated by our experiment code.
    n_subs : number of subjects to consider in conversion
    """

    for sub_int in xrange(1, n_subs + 1):
        for ses_int in xrange(1, 3):
            for run_int in xrange(1, 5):
                logfile = pjoin(fmri_log_dir, 'sub%02d_session%i_rionly_run%i_fmri.csv' % (sub_int, ses_int, run_int))
                tsvfile = pjoin(bids_dir, 'sub-%02d' % sub_int, 'ses-%i' % ses_int, 'func',
                                'sub-%02d_ses-%i_task-ri_run-%i_events.tsv' % (sub_int, ses_int, run_int))
                log2tsv_rionly(log_infile=logfile, tsv_outfile=tsvfile)


def convert_task_all(bids_dir='/home/my_data/exppsy/oliver/RIRSA/scratch/BIDS',
                     fmri_log_dir='/home/my_data/exppsy/oliver/RIRSA/raw/my_data/fmri_logs',
                     n_subs=6):
    # TODO: also make events for the second task (in session 2, runs 4-7, all stimuli)
    # for sub_int in xrange(1, n_subs + 1):
    #     for run_int in xrange(1, 5):
    #         pass

    logfile = pjoin(fmri_log_dir, 'sub%02d_session%i_allstim_run%i_fmri.csv' % (1, 1, 1))
    tsvfile = pjoin(bids_dir, 'sub-%02d' % 1, 'ses-%i' % 1, 'func',
                    'sub-%02d_ses-%i_task-all_run-%i_events.tsv' % (1, 1, 1))
    log2tsv_all(log_infile=logfile, tsv_outfile=tsvfile)
    return None


if __name__ == '__main__':
    convert_task_rionly(n_subs=6)
    convert_task_all()
