/**
 * Concat files.
 * @function task.worker.concatFiles
 * @param {object} config - Work configuration.
 * @param {string} config.src - Filename pattern. Glob.
 * @param {string} [config.ignore] - Ignore file pattern. Glob.
 * @param {string} config.dest - Destination file name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path'),
    debug = require('./_debug'),
    file = require('../../lib/file'),
    array = require('../../lib/array'),
    uniqueFilter = array.newUniqueFilter(),
    forceUnlink = file.forceUnlink,
    appendFile = file.appendFile,
    writeReadonlyFile = file.writeReadonlyFile,
    _expandGlobUnlessIgnored = require('./_expand_glob_unless_ignored');

module.exports = function (config, callback) {
    var async = require('async');
    var dest = path.resolve(config.dest),
        ignore = config.ignore && path.resolve(config.ignore),
        src = [].concat(config.src || '*').map(function (src) {
            return path.resolve(src);
        }).filter(uniqueFilter);
    _expandGlobUnlessIgnored(src, ignore, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        forceUnlink(dest, function (err) {
            if (err) {
                callback(err);
                return;
            }
            async.series(
                filenames.map(function (filename) {
                    return function (callback) {
                        appendFile(filename, dest, function (err) {
                            callback(err);
                        });
                    }
                }),
                function (err) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    fs.exists(dest, function (exists) {
                        if (!exists) {
                            callback(null);
                            return;
                        }
                        fs.chmod(dest, '444', function (err) {
                            if (!err) {
                                debug.didCreateFile(dest);
                            }
                            callback(err);
                        });
                    });
                }
            );
        });
    });
};