phantom.injectJs('vendor/qunit-coverage/core.js');

var suite = new Suite(phantom.args[0]);

var fs = suite.fs;
var workingDir = suite.workingDir;

console.log('Working dir: ' + workingDir);

function cleanFolders() {

    try { fs.removeTree(suite.sourcePath); } catch (e) {}
    try { fs.removeTree(suite.compiledPath); } catch (e) {}
    fs.makeTree(suite.sourcePath);
    fs.makeTree(suite.compiledPath);

}

function clearPath(path) {
    return path.replace(workingDir, '').split('..').join('_').split('\\').join('_').split('/').join('_').split(':').join('_');
}

function scanDir(dir, pattern, recursive) {

    console.log('  Dir: ' + dir);

    var res = [];
    var list = fs.list(dir);

    forEach(list, function(file) {

        var path = dir + '/' + file;

        if (file == '.' || file == '..') return;

        if (fs.isDirectory(path)) {

            if (recursive) res = res.concat(scanDir(path, pattern, recursive));

        } else {

            if (file.match(pattern)) {
                console.log('    File: ' + file);
                res.push(path);
            } else {
                console.log('    Skip: ' + file);
            }

        }

    });

    return res;

}

function getScripts() {

    console.log('Including files');

    var files = [];

    files.push(fs.absolute('vendor/qunit-coverage/qunit-coverage.js'));

    forEach(suite.config.includes, function(entry, key) {

        var originalPath = fs.absolute(entry.file);
        var newFile = clearPath(entry.file);
        var newPath = suite.sourcePath + '/' + newFile;

        if ('coverage' in entry && entry.coverage) {

            console.log('  Copy from: ' + originalPath);
            fs.copy(originalPath, newPath);
            files.push(newFile); // Relative!!!

        } else {

            console.log('     Use at: ' + originalPath);
            files.push(originalPath);

        }

    });

    return files;

}

function getTests() {

    console.log('Searching for tests');

    var files = [];

    forEach(suite.config.testCases, function(suite) {

        var tests = scanDir(workingDir + suite.location, suite.pattern, suite.recursive);
        forEach(tests, function(test) {
            files.push(test);
        });

    });

    console.log('Included tests');
    forEach(files, function(file){
        console.log('  Test: ' + file);
    });

    return files;

}

function getScriptsHTML(scripts) {
    console.log(scripts);
    var scriptsHtml = [];
    forEach(scripts, function(script) {
        scriptsHtml.push('<script src="' + script.split('\\').join('\\\\') + '" type="text/javascript"></script>');
    });

    return scriptsHtml.join('\n');

}

function getHTML(scriptsHtml) {
    var testContent = fs.read(suite.runnerTemplate);
    return testContent.replace('</body>', scriptsHtml + '</body>');

}

function writeHTML(html) {
    fs.write(suite.testRunnerSource, html, 'w');
}

try {

    cleanFolders();
    var scripts = getScripts();
    var tests = getTests();
    var scriptsHtml = getScriptsHTML([].concat(scripts, tests));
    var html = getHTML(scriptsHtml);
    writeHTML(html);

    phantom.exit();

} catch (e) {

    console.log('Critical error: ' + JSON.stringify(e));
    phantom.exit(1);

}

