'use strict';
var async = require('async');
var fs = require('fs');
var _ = require('lodash');
var config = require('../../config/config');

exports.concatJsFileContents = concatJsFileContents;
exports.concatJsonFileContents = concatJsonFileContents;
exports.concatFileContents = concatFileContents;
exports.readMultiFile = readMultiFile;

// --------------------- Utils Function ---------------------

function concatJsFileContents(buffers, cb) {
    cb(null, Buffer.concat(buffers));
}

function concatJsonFileContents(buffers, cb) {
    var json = {};
    _.forEach(buffers, function(item) {
        try {
            json = _.merge(json, JSON.parse(item.toString()));
        } catch (ex) {}
    });
    cb(null, json);
}

function concatFileContents(buffers, cb) {
    var r = '';
    _.forEach(buffers, function(item) {
        r += item.toString() + '\n';
    });
    cb(null, r);
}

function readMultiFile(files, cb) {
    async.map(
        files,
        readFile,
        cb
    );
}

// Cache lại nội dung file, dùng cho lần sau yêu cầu
var cacheFile = {};

function readFile(file, cb) {
    if (config.mode !== 'dev' && cacheFile[file]) {
        cb(null, cacheFile[file]);
    } else {
        fs.readFile(file, function(err, data) {
            if (!err) cacheFile[file] = data;
            cb(err, data);
        })
    }
}
