/**
 * Inherit prototype files unless already exists.
 * @function ci.worker._inheritPrototypeFiles
 * @param {object} config - Task configuration.
 * @param {string} [config.prototypeBaseDir] - Prototype base directory.
 * @param {string} config.pattern - File name glob patterns.
 * @param {string} config.ignore - Ignore  filename pattern. Glob.
 * @param {string} [config.destDir=apeman.current.basedir()] - Destination directory name.
 * @param {function} inherit - Function to inherit files.
 * @param {function} callback - Callback when done.
 * @protected
 * @ignore
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    lib = require('../../lib'),
    apeman = require('apeman'),
    file = lib.file,
    _expandGlobUnlessIgnored = require('./_expand_glob_unless_ignored'),
    debug = require('./_debug');

exports = module.exports = function (config, inherit, callback) {
    var prototypeBase = exports._prototypeBaseDir();
    if (!prototypeBase) {
        callback(null);
        return;
    }
    var ignore = [].concat(config.ignore || []).map(function (ignore) {
            return path.resolve(prototypeBase, ignore);
        }),
        destDir = path.resolve(config.destDir || exports._baseDir());
    var srcPattern = path.resolve(prototypeBase, config.pattern || '*');

    _expandGlobUnlessIgnored(srcPattern, ignore, function (err, src) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            src
                .map(function (src) {
                    return function (callback) {
                        var dest = path.resolve(destDir, path.relative(prototypeBase, src));
                        fs.exists(dest, function (exists) {
                            if (exists) {
                                callback();
                                return;
                            }
                            inherit(src, dest, function (err) {
                                if (!err) {
                                    debug.didCreateLink(dest, src);
                                }
                                callback(err);
                            });
                        });
                    }
                }),
            function (err) {
                callback(err);
            }
        );
    });
};


exports._baseDir = function () {
    return apeman.currentProject.basedir;
};

exports._prototypeBaseDir = function () {
    var prototypeProject = apeman.currentProject.prototypeProject;
    return prototypeProject && prototypeProject.basedir;
};