var multer = require('multer');
var mkdirp = require('mkdirp');
var config = require('../config');
var cdnHelper = require('../helpers/cdn.helper');

/*var upload = function (path) {
	return multer({storage: storage(path)});
};*/
var memoryUpload = multer({
    storage: multer.memoryStorage()
});

var makePath = function(path) {
    mkdirp(path, function (err) {
        if (err) throw err
        else return true;
    });
}

var cdnStorage = function(path) {
    return multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, path)
        },
        filename: function (req, file, cb) {
            cdnHelper.getUniqueName(path, file.originalname)
                .then(function(betterName) {
                    cb(null, betterName.replace(path, ''));
            });
        }
    });
}

var cdnUpload = function() {
    var cdnPath =  cdnHelper.getCDNPath(); 
    makePath(cdnPath);
    return multer({ 
        storage: cdnStorage(cdnPath) 
    });
}

module.exports = cdnUpload;