/**
 * Generate theme startup image files.
 * @function task.worker.generateThemeFaviconFiles
 * @param {object} config - Task configuration
 * @param {string} config.destDir - Destination directory.
 * @param {number} [config.count=12] - Number of favicons to generate.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */

var path = require('path'),
    util = require('util'),
    format = util.format,
    lib = require('../../lib'),
    image = lib.image,
    array = lib.array,
    file = lib.file,
    mkdirP = file.mkdirP,
    debug = require('./_debug'),
    shuffled = array.shuffled,
    _themeNameForIndex = require('./_theme_name_for_index'),
    text2image = image.text2image,
    apeman = require('apeman'),
    _randomColor = require('./_random_color'),
    _randomFont = require('./_random_font');

exports = module.exports = function (config, callback) {
    var destDir = path.resolve(config.destDir),
        current = apeman.current,
        appName = current.meta().name,
        count = config.count || 12,
        fontSize = 48,
        sizesFile = current.lookup('task/data/startup-images-sizes-data.js'),
        sizes = require(sizesFile);
    mkdirP(destDir, function (err) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            exports._startupImageData(sizes, fontSize, count)
                .map(function (imageData, i) {
                    return imageData.map(function (imageData) {
                        return {
                            imageData: imageData,
                            themeName: _themeNameForIndex(i)
                        }
                    });
                })
                .reduce(function (a, b) {
                    return [].concat(a).concat(b);
                }, [])
                .map(function (data) {
                    var imageData = data.imageData,
                        width = imageData.width,
                        height = imageData.height,
                        themeName = data.themeName;
                    return function (callback) {
                        var dest = path.resolve(destDir, exports._nameStartupImageFile(themeName, width, height));
                        text2image(
                            appName,
                            dest,
                            imageData,
                            function (err) {
                                if (!err) {
                                    debug.didCreateFile(dest);
                                }
                                setTimeout(function () {
                                    callback(err);
                                }, 1);
                            }
                        )
                    }
                }),
            function (err) {
                callback(err);
            }
        );
    });
};

exports._nameStartupImageFile = function (themeName, width, height) {
    return format('apple-touch-startup-image-theme-%s-%sx%s.png', themeName, width, height);
};

exports._startupImageData = function (sizes, fontSize, count) {
    var result = [];
    for (var i = 0; i < count; i++) {
        (function () {
            var fontFile = _randomFont().filename,
                themeColor = _randomColor();
                var colors = [ themeColor, '#FFF'].sort(function () {
                    return Math.random() - Math.random();
                });
            result.push(
                sizes.map(function (size) {
                    return {
                        backgroundColor: colors[0],
                        width: size.width,
                        height: size.height,
                        fontSize: fontSize,
                        color: colors[1],
                        fontFile: fontFile
                    };
                })
            );
        })();
    }
    return result;
};