/**
 * Generate _index.less files.
 * @function task.worker.generateIndexLessFile
 * @param {object} config - Task configuration.
 * @param {string} config.dir - Directory name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    lib = require('../../lib'),
    file = lib.file,
    debug = require('./_debug');
exports = module.exports = function (config, callback) {
    var dir = path.resolve(config.dir);
    exports._loadIndexLessTmpl(function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        fs.readdir(dir, function (err, filenames) {
            if (err) {
                callback(err);
                return;
            }
            var dest = path.resolve(dir, '_index.less');
            var content = tmpl({
                imports: filenames.filter(function (filename) {
                    return filename !== path.basename(dest);
                }),
                dirname: path.basename(dir)
            });
            file.writeReadonlyFile(dest, content, function (err) {
                if (!err) {
                    debug.didCreateFile(dest);
                }
                callback(err);
            });
        });

    });
};

exports._loadIndexLessTmpl = function (callback) {
    var filename = path.resolve(__dirname, '../../tmpl/less/_index.less.hbs');
    file.loadHbsTmpl(filename, callback);
};