/*
 *  Copyright 2015 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 controls a ribbon button that allows to include or exclude a page from SEO.<br/>
 * The button is toggle if page is currently excluded.
 * @private
 */
Ext.define('Ametys.plugins.web.page.controller.RobotsController', {
	extend: 'Ametys.web.controller.WebButtonController',
		
	/**
	 * @private
	 * @property {String[]} _pageIds The id the currently selected pages
	 */
	/**
	 * @private
	 * @property {String[]} _includedPageIds The ids of pages included in SEO files among the current selection
	 */
	/**
	 * @private
	 * @property {String[]} _excludedPageIds The ids of pages excluded in SEO files among the current selection
	 */
	
	/**
	 * @cfg {String} [icon-small] The path to the icon of the button in size 16x16 pixels when the current page has robots allowed
	 */
	/**
	 * @cfg {String} [icon-medium] The path to the icon of the button in size 32x32 pixels when the current page has robots allowed
	 */
	/**
	 * @cfg {String} [icon-large] The path to the icon of the button in size 48x48 pixels when the current page has robots allowed
	 */
	/**
	 * @cfg {String} [excluded-icon-small] The path to the icon of the button in size 16x16 pixels when the current page has robots disallowed
	 */
	/**
	 * @cfg {String} [excluded-icon-medium] The path to the icon of the button in size 32x32 pixels when the current page has robots disallowed
	 */
	/**
	 * @cfg {String} [excluded-icon-large] The path to the icon of the button in size 48x48 pixels when the current page has robots disallowed
	 */
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
	},
	
	/**
	 * Listener handler for modified messages
	 * @param {Ametys.message.Message} message the message
	 */
	 _onModified: function(message)
	 { 
		 if (this.updateTargetsInCurrentSelectionTargets (message))
		 {
			 this.refresh();
		 }
	 },
	 
	 updateState: function()
	 {
		this._getStatus(this.getMatchingTargets());
	 },
	
	/**
	 * Returns the ids of pages currently included in SEO files among the current selection
	 * @return {String[]} The pages' id
	 */
	getIncludedPageIds: function ()
	{
		return this._includedPageIds;
	},
	
	/**
	 * Returns the ids of pages currently excluded from SEO files among the current selection
	 * @return {String[]} The pages' id
	 */
	getExcludedPageIds: function ()
	{
		return this._excludedPageIds;
	},
	
	/**
	 * @private
	 * Get the status
	 * @param targets The page targets
	 */
	_getStatus: function (targets)
	{
		this.disable();
		
		this._pageIds = [];
		this._excludedPageIds = [];
		this._includedPageIds = [];
		
		if (targets.length > 0)
		{
			var pageIds = [];
			Ext.Array.each(targets, function(target) {
				pageIds.push(target.getParameters().id);
			});

			this.serverCall('getStatus',
					[pageIds], 
					Ext.bind(this._getStatusCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_WEB_PAGE_SEO_ROBOTS_REFRESH_ERROR}}",
							category: this.self.getName() 
						},
                        refreshing: true
					}
			);
		}
	},
	
	/**
	 * Callback for the button reloading process
	 * @param {Object} params the server's response
     * @param {String[]} params.excluded-pages The identifiers of excluded pages
     * @param {String[]} params.included-pages The identifiers of included pages
     * @param {String[]} params.parent-excluded-pages The identifiers of the excludes pages that are parent of any included pages 
	 */
	_getStatusCb: function(params)
	{
		this._updateTooltipDescription(this.getInitialConfig('description'), params);
		this._updateIcons(params);
		
		var me = this;
		Ext.Array.each (params['excluded-pages'], function (page) {
			me._pageIds.push(page.id);
			me._excludedPageIds.push(page.id);
		});
		
		Ext.Array.each (params['included-pages'], function (page) {
			me._pageIds.push(page.id);
			me._includedPageIds.push(page.id);
		});
		
		var isDisabled = this._isDisabled(params);
		var nbParentExcludedPages = params['parent-excluded-pages'].length;
		
		this.toggle(this._excludedPageIds.length > 0 || nbParentExcludedPages > 0);
		this.setDisabled((me._excludedPageIds.length + me._includedPageIds.length) == 0);
	},
	
	/**
	 * @protected
	 * Update the tooltip description according state of the current selection
	 * @param description The initial description. Can be empty.
	 * @param params The JSON result received
	 */
	_updateTooltipDescription: function (description, params)
	{
		description = this._handlingMultiple (description, 'page-included', params['included-pages']);
		description = this._handlingMultiple(description, "page-excluded", params['excluded-pages']);
		description = this._handlingMultiple(description, "page-parent-excluded", params['parent-excluded-pages']);
		description = this._handlingMultiple(description, "nomodifiable", params['nomodifiable-pages']);
		description = this._handlingMultiple(description, "noright", params['noright-pages']);
		
		this.setDescription (description);
	},
	
	/**
	 * @private
	 * Add text to description
	 * @param description The initial description to concatenate. Can be empty.
	 * @param {String} prefix The parameters prefix to used to retrieve the start and end description. The start and end description are retrieved from initial configuration with [prefix]-start-description and [prefix]-end-description
	 * @param {Object[]} pages The concerned pages. If empty, no text will be concatenated
	 */
	_handlingMultiple: function(description, prefix, pages)
	{
		if (pages.length > 0)
		{
			if (description != "")
			{
				description += "<br/><br/>";
			}
			
			description += this.getInitialConfig(prefix + "-start-description");
			for (var i=0; i < pages.length; i++)
			{
				if (i != 0) 
				{
					description += ", ";
				}
				description += pages[i].description;
			}
			description += this.getInitialConfig(prefix + "-end-description");
		}
		
		return description;
	},
	
	/**
	 * @private
	 * Add text to description
	 * @param description The initial description to concatenate. Can be empty.
	 * @param {String} paramName The name of initial configuration parameter
	 */
	_handleSingle: function (description, paramName)
	{
		if (description != "")
		{
			description += "<br/><br/>";
		}
		
		description += this.getInitialConfig(paramName);
		
		return description;
	},
	
	/**
	 * Update the icons of the button
	 * @param {Object} params the server's parameters
	 */
	_updateIcons: function(params)
	{
		var nbIncludedPages = params['included-pages'].length;
		var nbExcludedPages = params['excluded-pages'].length;
		var nbParentExcludedPages = params['parent-excluded-pages'].length;
		
		var iconGlyph = this.getInitialConfig()['icon-glyph'];
        var iconDecorator = this.getInitialConfig()['icon-decorator'];
        var iconDecoratorType = this.getInitialConfig()['icon-decorator-type'];
		
		if (nbExcludedPages > 0 || nbParentExcludedPages > 0)
		{
			iconGlyph = this.getInitialConfig()['excluded-icon-glyph'];
            iconDecorator = this.getInitialConfig()['excluded-icon-decorator'];
            iconDecoratorType = this.getInitialConfig()['excluded-icon-decorator-type'];
		}
        
        this.setGlyphIcon(iconGlyph);
        this.setIconDecorator(iconDecorator);
        this.setIconDecoratorType(iconDecoratorType);
	},
	
	/**
	 * Is the button disabled ?
	 * @param {Object} params the server's parameters
	 */
	_isDisabled: function (params)
	{
		var nbIncludedPages = params['included-pages'].length;
		var nbExcludedPages = params['excluded-pages'].length;
		var nbParentExcludedPages = params['parent-excluded-pages'].length;
		var nbNorightsPages = params['noright-pages'].length;
		
		return (nbIncludedPages == 0 && nbExcludedPages == 0 && nbParentExcludedPages > 0) || nbNorightsPages > 0;
	}
});