/**
 * Generate a fonts less file from available font files.
 * @function task.worker.generateFontsLessFiles
 * @param {object} config - Work configuration.
 * @param {string} config.destDir - Destination directory.
 * @param {string} config.ignore - Glob file patterns to ignore.
 * @param {string} [config.nameFormat='%s.less'] - Less file name format.
 * @param {string} config.fontFiles - Glob file patterns for font files to collect.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    debug = require('./_debug'),
    lib = require('../../lib'),
    file = lib.file,
    string = lib.string,
    util = require('util'),
    underscorize = string.underscorize,
    capitalize = string.capitalize,
    expandGlob = file.expandGlob,
    matchesGlob = file.matchesGlob,
    loadHbsTmpl = file.loadHbsTmpl,
    writeReadonlyFile = file.writeReadonlyFile;

exports = module.exports = function (config, callback) {
    var destDir = path.resolve(config.destDir),
        nameFormat = config.nameFormat || '%s.less',
        ignore = config.ignore;
    expandGlob(config.fontFiles, function (err, fontFiles) {
        if (err) {
            callback(err);
            return;
        }
        exports._loadFontsLessTmpl(function (err, tmpl) {
            if (err) {
                callback(err);
                return;
            }
            var imports = [].concat(config.imports || []).map(function (filename) {
                return path.relative(destDir, filename).replace(/\.less/, '');
            });
            require('async').series(
                fontFiles
                    .filter(function (filename) {
                        return ignore ? !matchesGlob(filename, ignore) : true;
                    })
                    .map(function (filename) {
                        return path.relative(path.dirname(destDir), filename);
                    })
                    .map(function (filename, i) {
                        var name = path.basename(filename, path.extname(filename));
                        var lowerName = name.replace(/[ \s\._]/g, '-').toLocaleLowerCase();
                        return {
                            dest: path.resolve(destDir, exports._nameFile(nameFormat, name)),
                            content: tmpl({
                                imports: imports,
                                name: name,
                                Name: capitalize(name),
                                lowerName: lowerName,
                                url: path.basename(filename),
                                styleName: ['font', lowerName].join('-'),
                                index: i + 1
                            })
                        }
                    })
                    .map(function (data) {
                        return function (callback) {
                            var dest = data.dest;
                            writeReadonlyFile(dest, data.content, function (err) {
                                if (!err) {
                                    debug.didCreateFile(dest);
                                }
                                callback(err);
                            });
                        }
                    }),
                function (err) {
                    callback(err);
                }
            );


        });
    });
};

exports._nameFile = function (nameFormat, name) {
    return util.format(
        nameFormat,
        underscorize(name.toLowerCase()).replace(/_/g, '-')
    );
};


/**
 * Load the fonts less templates.
 * @param callback
 * @private
 */
exports._loadFontsLessTmpl = function (callback) {
    var filename = path.resolve(__dirname, '../../tmpl/less/fonts.less.hbs');
    loadHbsTmpl(filename, callback);
};