/*
 * grunt-docarray
 * https://github.com/jrbarron/grunt-docarray
 *
 * Copyright (c) 2014 Jason Barron
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');

module.exports = function(grunt) {

    grunt.registerMultiTask('docarray', 'A Grunt plugin for convert ing an HTML document to a Javascript array.', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            preserveWhitespace: false,
            addExports: true,
            addJoin: true,
            joinSeparator: '\\n',
            header: '// This file was autogenerated by grunt-docarray at ' + new Date()
        });

        // Iterate over all specified file groups.
        this.files.forEach(function(f) {
            // Concat specified files.
            var srcs = f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            });

            var srcContent = srcs.map(function(filepath) {
                return grunt.file.read(filepath);
            });

            var vars = [];

            var destContent = srcContent.reduce(function(previous, current, index) {
                var varName = path.basename(srcs[index], '.html');
                vars.push(varName);

                var content = 'var ' + varName + ' = [\n';

                var newline = current.indexOf('\n');
                while (newline > -1) {
                    var skip = false;
                    var line = current.substring(0, newline);
                    current = current.substring(newline + 1);

                    if (!options.preserveWhite) {
                        line = line.trim();
                        if (line === '') {
                            skip = true;
                        }
                    }

                    if (!skip) {
                        line = line.replace(/\'/g, '\\\'');
                        content += '    \'' + line + '\',\n';
                    }
                    newline = current.indexOf('\n');
                }
                content += ']';
                if (options.addJoin) {
                    content += '.join(\'' + options.joinSeparator + '\')';
                }
                content += ';\n\n';
                return previous + content;

            }, options.header + '\n\n');

            if (options.addExports) {
                destContent = vars.reduce(function(previous, current) {
                    return previous + 'exports.' + current + ' = ' + current + ';\n';
                }, destContent + '\n\n');
            }

            // Write the destination file.
            grunt.file.write(f.dest, destContent);

            // Print a success message.
            grunt.log.writeln('File "' + f.dest + '" created.');
        });
    });

};
