/**
 * Batch to render pixabay gallery file.
 * @function serverside.batch.newPixabayGallery
 * @param {object} config - Batch configuration.
 * @param {string} config.contextLoader - Context loader file name.
 * @returns {object} - A new batch instance.
 * @author Taka Okunishi
 */
var path = require('path'),
    fs = require('fs'),
    lib = require('../../lib'),
    compile = lib.compile,
    file = lib.file,
    html = lib.html,
    writeReadonlyFile = file.writeReadonlyFile,
    prettifyHtml = html.prettifyHtml,
    mkdirP = file.mkdirP;

exports = module.exports = function (context) {
    var batchName = 'pixabayJadeRenderBatch',
        newBatchLogger = require('../logger/new_batch_logger');

    var logger = newBatchLogger(context),
        dataDir = path.resolve(context.PIXABAY_GALLERY_DATA_DIR_PATH),
        tmplFile = path.resolve(context.PIXABAY_GALLERY_TMPL_PATH),
        destDir = path.resolve(context.PIXABAY_GALLERY_HTML_DIR_PATH),
        dataFile = path.resolve(context.JADE_EN_DATA_FILE_PATH),
        dataMinFile = path.resolve(context.JADE_EN_MIN_DATA_FILE_PATH);


    logger.trace('Data directory: %s', dataDir);
    logger.trace('Template directory: %s', tmplFile);
    logger.trace('Destination directory: %s', destDir);

    return {
        name: batchName,
        run: function (callback) {
            logger.batchStart(batchName);

            function abort(err) {
                logger.fatal(err.stack || err);
                logger.batchFail(batchName);
                callback(err);
            }

            function success() {
                logger.batchSuccess(batchName);
                callback(null);
            }

            var tmpl = require(tmplFile);
            fs.readdir(dataDir, function (err, filenames) {
                if (err) {
                    callback(err);
                    return;
                }
                require('async').series(
                    filenames
                        .map(function (filename) {
                            return path.resolve(dataDir, filename);
                        })
                        .map(function (filename) {
                            var photoData = require(filename);
                            var name = path.basename(filename, path.extname(filename)).replace('-data', '');
                            return function (callback) {
                                var dest, rendered, data;
                                logger.trace('SHOULD_MINIFY_HTML=%s', context.SHOULD_MINIFY_HTML);
                                try {

                                    if (context.SHOULD_MINIFY_HTML) {
                                        data = require(dataMinFile);
                                        data.photoData = photoData;
                                        rendered = tmpl(data);
                                        dest = path.resolve(destDir, name + 'min.html');
                                    } else {
                                        data = require(dataFile);
                                        data.photoData = photoData;
                                        rendered = prettifyHtml(tmpl(data));
                                        dest = path.resolve(destDir, name + '.html');
                                    }
                                } catch (e) {
                                    callback(e);
                                    return;
                                }
                                mkdirP(path.dirname(dest), function (err) {
                                    if (err) {
                                        abort(err);
                                        return;
                                    }
                                    writeReadonlyFile(dest, rendered, function (err) {
                                        if (!err) {
                                            logger.debug('File rendered: %s', dest);
                                        }
                                        callback(err);
                                    });
                                });
                            }
                        }),
                    function (err) {
                        if (err) {
                            abort(err);
                        } else {
                            success();
                        }
                    }
                )
            });

        }
    }
};