var kebabToPascal = require ('../vn/string-util').kebabToPascal;

module.exports = new Class
({
	 basePath: null
	,path: null
	,moduleName: null
	,callbacks: []
	,localeReady: false
	,jsReady: false
	,uiReady: false
	,error: false
	,ready: false

	,initialize: function (basePath, path)
	{
		var absPath = basePath +'/'+ path;

		var aux = path.split ('/');
		var moduleName = aux[aux.length - 1];

		Vn.Locale.load (absPath,
			this.onLocaleReady.bind (this));
		Vn.includeJs (absPath +'/'+ moduleName +'.js',
			this.onJsReady.bind (this));
		Vn.loadXml (absPath +'/ui.xml',
			this.onUiReady.bind (this));

		this.basePath = basePath;
		this.path = path;
		this.moduleName = moduleName;
	}

	,getCssPath: function ()
	{
		return this.basePath +'/'+ this.path +'/style.css';
	}

	,includeCss: function ()
	{
		Vn.includeCss (this.getCssPath ());
	}

	,unload: function ()
	{
		Vn.excludeCss (this.getCssPath ());
	}
	
	,load: function (callback)
	{
		if (this.ready)
		{
			this.includeCss ();
			callback (this);
		}
		else
			this.callbacks.push (callback);
	}

	,onLocaleReady: function (success)
	{
		this.localeReady = true;
		this.onReady ();
	}

	,onJsReady: function (success)
	{
		this.jsReady = true;
		this.error = !success;
		this.onReady ();
	}
	
	,onUiReady: function (success)
	{
		this.uiReady = true;
		this.error = !success;
		this.onReady ();
	}

	,onReady: function ()
	{
		if (!(this.localeReady && this.jsReady && this.uiReady))
			return;

		this.ready = true;

		var klassName = kebabToPascal (this.moduleName);
		
		try {
			this.klass = Hedera[klassName];
		}
		catch (e)
		{
			this.error = true;
			console.error (e);
		}

		var callbacks = this.callbacks;
		this.callbacks = null;
		this.includeCss ();

		for (var i = 0; i < callbacks.length; i++)	
			callbacks[i] (this);
	}
});