/*
 *  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 controller allows to schedule the opening of the current selected survey<br/>
 * The button's icon represents the current opening status of the survey.
 * @private
 */
Ext.define(
	'Ametys.plugins.survey.controller.ScheduledOpeningController', 
	{
		extend: 'Ametys.ribbon.element.ui.ButtonController',

		/**
		 * @property {String[]} [_surveyIds=[]] List of identifiers of surveys concerned by the action of the controller
		 * @private
		 */
		/**
		 * @cfg {String} [on-icon-small] The small icon when there is a opening scheduled
		 */
		/**
		 * @cfg {String} [on-icon-medium] The medium icon when there is a opening scheduled
		 */
		/**
		 * @cfg {String} [on-icon-large] The large icon when there is a opening scheduled
		 */
		
		/**
		 * @cfg {String} [forthcoming-icon-small] The small icon when there is a forthcoming opening
		 */
		/**
		 * @cfg {String} [forthcoming-icon-medium] The medium icon when there is a forthcoming opening
		 */
		/**
		 * @cfg {String} [forthcoming-icon-large] The large icon when there is a forthcoming opening
		 */
		
		/**
		 * @cfg {String} [outofdate-icon-small] The small icon when there is an outdated opening
		 */
		/**
		 * @cfg {String} [outofdate-icon-medium] The medium icon when there is an outdated opening
		 */
		/**
		 * @cfg {String} [outofdate-icon-large] The large icon when there is an outdated opening
		 */
		
		constructor: function(config)
		{
			this._surveyIds = [];
			this.callParent(arguments);
			
			Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
		},
		
		/**
		 * @private
		 * Listener handler for modified messages
		 * @param {Ametys.message.Message} message the message
		 */
		_onModified: function(message)
		{
			if (this.updateTargetsInCurrentSelectionTargets(message))
	        {
	            this.refresh();
	        }
		},
		
		/**
		 * Get the matching targets that match conditions
		 * @return {Ametys.message.MessageTarget[]} targets filling all conditions.
		 */
		getAllRightSurveyTargets: function ()
		{
			var matchingTargets = this.getMatchingTargets();
			var me = this;
			
			return Ext.Array.filter (matchingTargets, function (target) {
				return Ext.Array.contains(me._surveyIds, target.getParameters().id)
			});
		},
		
		updateState: function()
		{
			this._getStatus(this.getMatchingTargets());
		},
		
		
		/**
		 * @private
		 * Get the status
		 * @param targets The survey targets
		 */
		_getStatus: function (targets)
		{
			this._surveyIds = [];
			this.disable();
			
			if (targets.length > 0)
			{
				var surveyIds = [];
				Ext.Array.each(targets, function(target) {
					surveyIds.push(target.getParameters().id);
				});

				this.serverCall('getStatus',
						[surveyIds], 
						Ext.bind(this._getStatusCb, this),
						{ 
							errorMessage: false,
                            refreshing: true
						}
				);
			}
		},
		
		/**
		 * @private
		 * Callback for the button's status computation process
		 * @param {Object} params the server's response
		 * @param {String} params.scheduled-surveys the surveys having a scheduled opening
		 * @param {String} params.scheduled-valid-surveys the surveys within opening interval
		 * @param {String} params.scheduled-outofdate-surveys the surveys outside opening interval
		 * @param {String} params.scheduled-forthcoming-surveys the forthcoming surveys
		 * @param {Object} args the callback arguments
		 */
		_getStatusCb: function(params, args)
		{
			this._updateTooltipDescription(this.getInitialConfig('default-description'), params);
			this._updateIcons(params);
			
			this.toggle(params['scheduled-surveys'].length > 0);
			
			var allRightSurveys = params['allright-surveys'];
			if (allRightSurveys.length > 0)
			{
				for (var i=0; i < allRightSurveys.length; i++)
				{
					this._surveyIds.push(allRightSurveys[i].id)
				}
				this.enable();
			}
			else
			{
				this.disable();
			}
		},
		
		
		/**
		 * @private
		 * 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, "scheduled-survey-valid", params['scheduled-valid-surveys']);
			description = this._handlingMultiple(description, "scheduled-survey-outofdate", params['scheduled-outofdate-surveys']);
			description = this._handlingMultiple(description, "scheduled-survey-forthcoming", params['scheduled-forthcoming-surveys']);
			
			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[]} surveys The concerned surveys. If empty, no text will be concatenated
		 */
		_handlingMultiple: function(description, prefix, surveys)
		{
			if (surveys.length > 0)
			{
				if (description != "")
				{
					description += "<br/><br/>";
				}
				
				description += this.getInitialConfig(prefix + "-start-description");
				for (var i=0; i < surveys.length; i++)
				{
					if (i != 0) 
					{
						description += ", ";
					}
					description += surveys[i].description;
				}
				description += this.getInitialConfig(prefix + "-end-description");
			}
			
			return description;
		},
		
		/**
		 * @private
		 * Set the icons according to the button's status
		 * @param {Object} params the parameters
		 * @param {String} params.scheduled-surveys the surveys having a scheduled opening
		 * @param {String} params.scheduled-valid-surveys the surveys within opening interval
		 * @param {String} params.scheduled-outofdate-surveys the surveys outside opening interval
		 * @param {String} params.scheduled-forthcoming-surveys the forthcoming surveys
		 */
		_updateIcons: function (params)
		{
			var nbScheduledSurveys = params['scheduled-surveys'].length;
			var nbValidSurveys = params['scheduled-valid-surveys'].length;
			var nbOutOfDateSurveys = params['scheduled-outofdate-surveys'].length;
			var nbForthComingSurveys = params['scheduled-forthcoming-surveys'].length;
			
			var iconGlyph, iconDecorator;
			
			if (nbScheduledSurveys > 0 && nbValidSurveys > 0)
			{
				iconGlyph = this.getInitialConfig()['on-icon-glyph'];
				iconDecorator = this.getInitialConfig()['on-icon-decorator'];
			}
			
			if (nbScheduledSurveys > 0 && nbForthComingSurveys > 0)
			{
				iconGlyph = this.getInitialConfig()['forthcoming-icon-glyph'];
				iconDecorator = this.getInitialConfig()['forthcoming-icon-decorator'];
			}
			
			if (nbScheduledSurveys > 0 && nbOutOfDateSurveys > 0)
			{
				iconGlyph = this.getInitialConfig()['outofdate-icon-glyph'];
				iconDecorator = this.getInitialConfig()['outofdate-icon-decorator'];
			}
			
			if (nbScheduledSurveys == 0)
			{
				iconGlyph = this.getInitialConfig()['icon-glyph'];
				iconDecorator = this.getInitialConfig()['icon-decorator'];
			}
			
			this.setGlyphIcon(iconGlyph);
			this.setIconDecorator(iconDecorator);
		}
	}
);