var fs = require('fs');
var path = require('path');

// Machine maps are loaded here into memory at require time.
module.exports = fs.readdirSync(path.resolve(path.join(__dirname,'lib'))).reduce(function(memo, basename) {
    if (basename[0] === '.') return memo;
    if (!(/.json$/.test(path.extname(basename)))) return memo;
    var doc;
    try {
        doc = JSON.parse(fs.readFileSync(path.resolve(path.join(__dirname,'lib',basename)), 'utf8'));
    } catch (err) {
        if (err) throw new Error(basename + ': ' + err.message);
    }
    memo[doc.id] = doc;
    return memo;
}, {});

// Ensure mapid is set consistently.
for (var id in module.exports) module.exports[id].id = id;

// Replace tilesource {dirname} token
for (var id in module.exports) if (module.exports[id].tilesource) {
    module.exports[id].tilesource = module.exports[id].tilesource.replace('{dirname}', __dirname);
}

Object.defineProperty(module.exports, 'dirname', {
    value: function(mapid) {
        if (!module.exports[mapid]) return false;
        return path.dirname(module.exports[mapid].tilesource.replace('vector://', ''));
    },
    enumerable: false
});

