/*
 *  Copyright 2014 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Query Factory
 * This factory create query object follow type
 * @private
 */
Ext.define('Ametys.plugins.queriesdirectory.model.QueryFactory', {
	
	singleton: true,
	
	/**
	 * @private
	 * @property {Object} _queries The registered queries
	 */
    _queries: {},
    
    /**
     * Registers a new type of query
     * @param {String} type The query unique type
     * @param {Function} queryJSClass The JS class for this type
     */
    registerQuery: function (type, queryJSClass)
    {
    	this._queries[type] = queryJSClass;
    },
    
    /**
     * Get the registered query types
     * @return {String[]} the types
     */
    getQueryTypes: function ()
    {
    	return Object.keys(this._queries);
    },
    
	/**
	 * Function to create the query
	 * @param {String} type the type of the query
     * @param {Boolean} queryId The identifier of the query
	 * @param {Object} content The content query
	 * @param {String} [title] The title of the query might be passed (can be null too).
	 * @param {Boolean} [readOnly=false] Set to 'true' to create query in read-only mode.
	 * @return {Ametys.plugins.queriesdirectory.model.AbstractQuery} The query
	 */
	create: function (type, queryId, content, title, readOnly) 
	{
		var queryJSClass = this._queries[type];
		
		if (!queryJSClass)
		{
			throw "Unknown query type '" + type + "'";
		}
		
		if (typeof eval(queryJSClass) != 'function')
		{
			throw "There is no registered query for type '" + widgetType + "'";
		}
		
		var q = Ext.create(queryJSClass, content, readOnly);
		q.setQueryId(queryId);
        
		if (title)
		{
			q.setTitle(title);
		}
		
		return q;
	}

});