/**
 * Watch files to execute task.
 * @function task.worker.watchFilesForTask
 * @param {object} config - Work configuration.
 * @param {string} config.task - Task name to execute.
 * @param {number} [config.timeout=50000] - Timeout milliseconds.
 * @param {string|string[]} config.dir - Directories to watch. Glob.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path'),
    debug = require('./_debug'),
    file = require('../../lib/file'),
    expandGlob = file.expandGlob,
    filterDirectory = file.filterDirectory,
    format = require('util').format;

exports = module.exports = function (config, callback) {
    var taskName = config.task,
        delay = 500,
        timeout = config.timeout || 8 * 1000;
    expandGlob(config.dir, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        filterDirectory(filenames, function (err, dirnames) {
            if (err) {
                callback(err);
                return;
            }
            dirnames.forEach(function (dirname) {
                fs.watch(dirname, function (ev, filename) {
                    debug('File changed %s', filename);
                    try {
                        exports._executeTask(taskName, delay, timeout, function (e) {
                            console.error(e.stack || e);
                        });
                    } catch (e) {
                        console.error(e.stack || e);
                    }
                });
                debug('Start watch:%s', dirname);
            });
        });
    });
    callback();
};


exports._executeTask = function (taskName, delay, timeout, errCallback) {
    var apeman = require('apeman');
    var timer = exports._timers[taskName];
    if (timer) clearTimeout(timer);
    exports._timers[taskName] = setTimeout(function () {
        var errorTimer = setTimeout(function () {
            var msg = format('Task "%s" took to too long. %s ms passed.', taskName, timeout);
            errCallback(msg)
        }, timeout);

        apeman.task(taskName, {}, function () {
            clearTimeout(errorTimer);
        });
    }, delay);
};
exports._timers = {};


