var loggerManager = require('./loggerManager.js'),
	EventEmitter = require('events').EventEmitter,
	assert = require('assert'),
	util = require('util'),
	_ = require('underscore'),
	path = require('path'),
	fs = require('fs');
	
// Get a reference to the active logger to avoid need to get it for each call.
var logger = loggerManager.get();

//Watch for updates to the logger and update our reference when it changes.
loggerManager.on('updated', function(lgr) {
	logger = lgr;
});

var TypeManager = function() {
	var descriptors = [],
		typeManager = this;

	this.registerType = function(descriptor) {
		var instance;
		if (_.isString(descriptor)) {
			debugger;
			logger.info('Retrieving descriptor from "' + descriptor + '"');
			instance = JSON.parse(fs.readFileSync(descriptor));
		} else {
			instance = descriptor;
		}
		assert(instance.name, '"name" is a required property.');
		assert(instance.type, '"type" is a required property.');
		logger.info('Registering ' + instance.name + ' descriptor as type "' + instance.type + '"');
		switch (instance.type) {
			case 'STATIC':
				descriptors.push(instance);
				break;
		}
		typeManager.emit('registered', instance);
	};

	/**
	 * registerTypes allows you to register mulitiple types.
	 *
	 * Note: This function will block to avoid starting the server in
	 * an incomplete state.
	 *
	 * @param descriptors A path to a directory containing type descriptors, an array 
	 * type descriptor file names or an array of type descriptor instances.
	 */
	this.registerTypes = function(descriptors) {
		var references;
		// If a path was passed in, retrieve the file list.
		if (_.isString(descriptors)) {
			logger.info('Retrieving a list of descriptor files from "' + descriptors + '"');
			references = fs.readdirSync(descriptors);
			references = _.map(references, function(reference) {
				return path.join(descriptors, reference);
			});
		// If an array of paths were passed, store a reference in paths for
		// later processing.
		} else if (descriptors.length && _.isString(descriptors[0])) {
			references = descriptors;
		}

		
		_.each(references, function(reference) {
			// If the reference is a string, pass it on as long as it has a ".json" extension.
			if (_.isString(reference)) {
				if (reference.substr(-5) === '.json') {
					typeManager.registerType(reference);
				}
			// If the reference is descriptor instances, just pass it on
			// as they are.
			} else {
				typeManager.registerType(reference);
			}
		});
	};

	EventEmitter.call(this);
};

util.inherits(TypeManager, EventEmitter);

module.exports = TypeManager;