/**
 * A SQL-based sort and filter.  Unlike SortedFilter, this does not extract source data from the document, or use data groups, or interacts with DOM.
 *
 * Requires:
 *	TrimQueryUtilities.js
 *  TrimPath.js
 */
function SimpleSortedFilter()
{
	var itsData;
	var itsQueryEngine;
	var itsTableName;
	var itsWhere;
	var itsOrderBy;
	var itsSortOrder;
	var itsLastWhere;
	var itsLastOrderBy;
	var itsLastData;

	Publisher(this);
	
	this.sortAndFilter = function(inWhere, inOrderBy, inSortOrder)
	{
		var theSQL;
		var theProcessedData = Objects.clone(itsData);

		inWhere = inWhere || itsWhere;
		inOrderBy = inOrderBy || itsOrderBy;
		inSortOrder = inSortOrder || itsSortOrder;

		if (itsData == itsLastData && inWhere == itsLastWhere && inOrderBy == itsLastOrderBy)			
			return itsLastData;

		theSQL =
		"SELECT "
			+ itsTableName
			+ ".* FROM "
			+ itsTableName
			+ (inWhere ? " WHERE " + inWhere : "")
			+ (inOrderBy ? " ORDER BY " + inOrderBy : "")
			+ (inSortOrder ? " " + inSortOrder : "");

        if(itsData[itsTableName].length == 0){
           return theProcessedData;
        }else{
           theProcessedData[itsTableName] = itsQueryEngine.parseSQL(theSQL).filter(itsData);
        }



        itsLastWhere = inWhere;
		itsLastOrderBy = inOrderBy;
		//itsLastData = itsData;
		itsLastData = theProcessedData;

		this.notifySubscribers(theProcessedData, inWhere, inOrderBy, inSortOrder);
		return theProcessedData;
	};


	this.setSortAndFilter = function(inWhere, inOrderBy)
	{
		itsWhere = inWhere;
		itsOrderBy = inOrderBy;
		itsSortOrder = inSortOrder
	};


	this.clearSortAndFilter = function()
	{
		itsWhere = null;
		itsOrderBy = null;
		itsSortOrder = null;
	};


	this.setWhere = function(inWhere)
	{
		itsWhere = inWhere;
	};


	this.getWhere = function()
	{
			return itsWhere;
	};


	this.clearWhere = function()
	{
		itsWhere = null;
	};


	this.setOrderBy = function(inOrderBy)
	{
		itsOrderBy = inOrderBy;
	};

	
	this.clearOrderBy = function()
	{
		itsOrderBy = null;
	};
	
	this.setSortOrder = function(inSortOrder)
	{
		itsSortOrder = inSortOrder;
	};

	
	this.clearSortOrder = function()
	{
		itsSortOrder = null;
	};


	this.getTableName = function()
	{
		return (itsTableName);
	};


	this.setTableName = function(inTableName)
	{
		itsTableName = inTableName;
	};


	this.getData = function()
	{
		return (itsData);
	};


	this.setData = function(inData)
	{
		itsData = inData;
		itsQueryEngine = TrimPath.makeQueryLang(TrimQueryUtilities.inferTableDefinitions(itsData));
	};
}
