/*
 *  Copyright 2018 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 tool display all contents referencing with at least the same selected entries of a reference table
 * @private
 */
Ext.define('Ametys.plugins.cms.content.tool.SearchReferencingContentsWithSameValuesTool', {
	extend: "Ametys.plugins.cms.search.ContentSearchTool",
		
	/**
	 * @private
	 * @property {Ext.Template} _hintTpl The template for hint
	 */
	_hintTpl: Ext.create ('Ext.Template', ["{{i18n PLUGINS_CMS_UITOOL_REFERENCE_TABLE_SAME_REFERENCING_CONTENTS_HINT}}"]),
	
    allowAdditionalExtensions: false,
    
	/**
	 * @inheritdoc
	 */
	createPanel: function()
	{
	    var panel = this.callParent(arguments);
		
	    // Insert a hint container at first position.
	    panel.addDocked({
			xtype: 'component',
			ui: 'tool-hintmessage',
            itemId: 'hint-message',
			dock: 'top',
			html: ''
		}, 0);
		
		return panel;
	},
    
    setParams: function(params)
    {
        this.callParent(arguments);
        
        this.serverCall('getSearchContext', [params.contentId, params.referenceField, params.referenceValues], this._updateInfos, {
            errorMessage: "{{i18n PLUGINS_CMS_UITOOL_REFERENCE_TABLE_SAME_REFERENCING_CONTENTS_ERROR}}"
        });
    },
	
	/**
	 * @inheritdoc
	 */
	getContextualParameters: function()
	{
		return {
			contentId: this.getParams().contentId,
			referenceField: this.getParams().referenceField,
			referenceValues: this.getParams().referenceValues,
			language: this.getParams().language
		};
	},
	
	/**
	 * Callback function after retrieving information on entries
	 * @param {Object} result The JSON server response
	 * @private
	 */
	_updateInfos: function(result)
	{
        var refValues = result.refValues || {};
        
        var refTitles = [];
        Ext.Object.eachValue(refValues, function (value) {
		    refTitles.push(value);
		});
        
		var html = this._hintTpl.applyTemplate({
            values: refTitles.sort().join(', '), 
            refContentType: result.attribute.refContentType,
            referenceTable: result.referenceTable.label,
            attributeLabel: result.attribute.label
        });
        
		this.mainPanel.getDockedComponent('hint-message').update(html);
	}
});