var utils  = require('../utils');

/**
 * session
 *
 * Takes a list of files and creates a set of file names that occur in subject
 * directories. Then generates a warning if a given subject is missing any 
 * files from the set.
 */
var session = function missingSessionFiles(fileList) {
    var subjects = [];
    var issues = [];
    for (var key in fileList) {
        var file = fileList[key];
        var filename;
        var path = utils.files.relativePath(file);
        var subject;
        //match the subject identifier up to the '/' in the full path to a file.
        var match = path.match(/sub-(.*?)(?=\/)/);
        if (match === null) {
            continue;
        } else {
            subject = match[0];
        }
        // initialize an empty array if we haven't seen this subject before
        if (typeof(subjects[subject]) === 'undefined') {
            subjects[subject] = [];
        }
        // files are prepended with subject name, the following two commands 
        // remove the subject from the file name to allow filenames to be more
        // easily compared
        filename = path.substring(path.match(subject).index + subject.length);
        filename = filename.replace(subject, '');
        subjects[subject].push(filename);
    }
      
    var subject_files = [];
    for (var subject in subjects) {
        subject_files = subject_files.concat(subjects[subject])
    }
    // Converting to a Set removes all duplicates
    all_files = new Set(subject_files);

    // Converting it back to an array for easy iteration
    all_files = Array.from(all_files);
    for (var subject in subjects) {
        for (var set_file in all_files) {
            if (subjects[subject].indexOf(all_files[set_file]) === -1) {
                issues.push(new utils.Issue({
                    file: all_files[set_file],
                    evidence: "Subject: " + subject + "; Missing file: " + all_files[set_file],
                    code: 39
                }));
            } 
        }
    }
    return issues;
};

module.exports = session;

@@ -1218,16 +1218,21 @@
 bject, '
+%3Csub%3E
 ');%0A    
@@ -1750,24 +1750,160 @@
 ) === -1) %7B%0A
+                filename = all_files%5Bset_file%5D.replace('%3Csub%3E', subject);%0A                file.relativePath = '/' + subject + filename;%0A
             
@@ -1962,35 +1962,20 @@
   file: 
-all_files%5Bset_file%5D
+file
 ,%0A      
@@ -2043,35 +2043,24 @@
 le: %22 + 
-all_files%5Bset_file%5D
+filename
 ,%0A      

put subject name place holder in so we can properly recreate filenames after the union of all session files is created. Fixed issue with file name is Issue object being undefined