/**
 * LanternJS MVC Framework v0.1
 * http://lanternjs.com/
 * 
 * Copyright (c) 2011 Yaroslav Tkachenko http://sap1ens.ru
 * GNU General Public License http://www.gnu.org/licenses/gpl.html
 */
function Model () {
	this.actions = {};	
	this._storage = {};	
	this._defaults = {};	
	this.ext = 'json';
}

/**
 * It can work with variables, objects or functions. 
 * If value is Function it will work like Setter
 * @param {String} key
 * @param {Object|String|Number} value
 */
Model.prototype.set = function(key, value) {
	if(!this._storage[key]) this._defaults[key] = value;
	this._storage[key] = value;
}

/**
 * It can work like Getter if saved value is function
 * @param {String} key
 * @return {Object|String|Number}
 */
Model.prototype.get = function(key) {
	if(typeof this._storage[key] == 'Function')
		return this._storage[key]();
	else
		return this._storage[key];
}

Model.prototype.remove = function(key) {
	delete this._storage[key];
	if(this._defaults[key]) delete this._defaults[key];
}

Model.prototype.def= function(key, replace) {
	if(replace)
		this._storage[key] = this._defaults[key];
	
	if(typeof this._defaults[key] == 'Function')
		return this._defaults[key]();
	else
		return this._defaults[key];	
}

Model.prototype.keys = function() {
	var keys = [];
	for(prop in this._storage) if (this._storage.hasOwnProperty(prop)) {
    	keys.push(prop);
	}
	return keys;
}

Model.prototype.clean = function() {
	this._storage = {};
	this._defaults = {};
}

Model.prototype.asJSONString = function() {
	return __.JSON.getString(this._storage);
}

/**
 * Can be used for loading data from Object. Second parameter is not required, but if replace is true it will overwrite storage object, else - just add new keys
 * @param {Object} obj
 * @param {Boolean} replace
 */
Model.prototype.loadFromJSONObject = function(obj, replace) {
	if(replace) {
		this._storage = obj;
		this._defaults = obj;
	} else {
		for(var i in obj) {
			this._storage[i] = obj[i];
			this._defaults[i] = obj[i];
		}
	}
}

/**
 * Can be used for loading data from JSON, represented as String. Second parameter is not required, but if replace is true it will overwrite storage object, else - just add new keys
 * @param {String} str
 * @param {Boolean} replace
 */
Model.prototype.loadFromJSONString = function(str, replace) {
	this.loadFromJSONObject(__.JSON.getObject(str), replace)
}

Model.prototype.dataLoad = function(key, path) {
	var data = __.load(__.getRootUrl() + 'data/' + path.replace(/\./g, '/') + '.' + this.ext);
	if(!this._storage[key])
		this._defaults[key] = __.JSON.getObject(data);	
		
	this._storage[key] = __.JSON.getObject(data);	
}

