/*
 *  Copyright 2017 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.
 */

/**
 * This class provides a web widget to select one ore more orgunit.<br>
 * This widget is registered for fields of type Ametys.form.WidgetManager#TYPE_CONTENT.
 */
Ext.define('Ametys.plugins.odf.web.widget.SelectWebOrgUnit', {
    extend : 'Ametys.odf.widget.SelectOrgUnit',
    
    xtype: 'edition.select-web-orgunit',
    modelId: 'search-ui.orgunit-restriction',
    
    /**
     * @private
     * @property {String} _rootOrgUnitId The root orgunit (with restriction)
     */
    
    selectContentsBySearch: function()
    {
    	this.getRootOrgUnit(function (rootId){
    		Ametys.odf.helper.ChooseOrgUnit.open({
                multiple: this.multiple,
                values: this.getValue() || [],
                callback:  Ext.bind(this._selectOrgUnitsCb, this),
                allowCreation: this.ouAllowCreation == true || this.ouAllowCreation == 'true',
                rootOrgUnitId: rootId
            });
    	}, this);
    },
    
    _onStoreBeforeLoad: function(store, operation)
    {
    	if (this._rootOrgUnitId == null)
    	{
            var params = operation.getParams() || {};
            var callback = operation.getCallback() || Ext.emptyFn;
    		// Root orgunit is not yet determined, cancel search and reload store after getting the id of root orgunit
    		this.getRootOrgUnit(function(rootId){
    			store.load({
    				params: params,
    				callback: callback
    			});
    		})
    		return false; // cancel search
    	}
    	
    	this.callParent(arguments);
    	
    	// Force id of root orgunit
    	var me = this;
    	Ext.apply(operation.getParams().values, {
    		'reference-orgUnitAncestor-eq': me._rootOrgUnitId,
    	});
    },
    
    /**
     * Get the root orgUnit id
     * @param {Function} callback the callback function
     * @param {Object} scope the scope
     */
    getRootOrgUnit: function(callback, scope)
    {
    	if (this._rootOrgUnitId)
    	{
    		callback.call(this, this._rootOrgUnitId)
    	}
    	else
    	{
    		Ametys.data.ServerComm.callMethod({
    			role: "org.ametys.plugins.odfweb.restrictions.OdfProgramRestrictionManager",
    			methodName: "getRestrictionRootOrgUnitId",
    			parameters: [Ametys.getAppParameter("siteName")],
    			callback: {
    				handler:this._getRootOrgUnitCb,
    				scope: this,
    				arguments: [callback, scope || this]
    			},
    			waitMessage: false
    		});
    	}
    },
    
    /**
     * @private
     * Callback to set the root orgUnit id
     * @param {String} rootId The orgUnit root id
     * @param {Object[]} args The additionnal arguments
     */
    _getRootOrgUnitCb: function (rootId, args)
    {
    	this._rootOrgUnitId = rootId;
    	
    	if(Ext.isFunction(args[0]))
    	{
    		args[0].call(args[1] || this, rootId);
    	}
    }
});