var util = require('util');
var fs = require('fs');
var dive = pb.PluginService.require('clean-pencilblue', 'dive');

function FsMediaProvider(parentDir){
    FsMediaProvider.super_.call(this, parentDir);
};

util.inherits(FsMediaProvider, pb.FsMediaProvider);

FsMediaProvider.PARALLEL_LIMIT = 20;

FsMediaProvider.prototype.bulkDelete = function(paths, callback){
    var parentDir = this.parentDir;
    async.eachLimit(paths, FsMediaProvider.PARALLEL_LIMIT, function(path, cb){
        var ap = pb.FsMediaProvider.getMediaPath(parentDir, path);
        fs.exists(ap, function(exists){
            if(!exists){ return cb(); }
            fs.unlink(ap, cb);
        });
    }, callback);
};

FsMediaProvider.prototype.truncatePath = function(absolutePath, point){
    var parent = this.parentDir;
    var removed = path.join(DOCUMENT_ROOT, point);
    var regexp = new RegExp('^' + removed);
    return absolutePath.replace(regexp, '');
};

FsMediaProvider.prototype.getAllRawFiles = function(callback){
    var self = this;
    var parent = this.parentDir;
    var mpath = pb.FsMediaProvider.getMediaPath(parent, '/media');
    var files = [];
    dive(mpath, function(err, file) {
        if(err) { throw err; }
        file = self.truncatePath(file, parent);
        files.push(file);
    }, function() {
        return callback(null, files);
    });
};

module.exports = FsMediaProvider;