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

/**
 * Schedule the scheduled of survey
 */
Ext.define(
	'Ametys.plugins.survey.ScheduleOpening', 
	{
		singleton: true,
		
		/**
		 * @private
		 * @property {Ametys.window.DialogBox} _box The dialog box
		 */
	
		/**
		 * @private
		 * @property {Ext.form.Basic} _form the form
		 */
		
		/**
		 * @private
		 * @property {Boolean} _initialized Is the dialog box initialized ?
		 */
		
		/**
		 * Schedule the scheduled of a survey
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling this function
		 */
		act: function(controller)
		{
			var targets = controller.getAllRightSurveyTargets();
			if (targets.length > 0)
			{
				this._delayedInitialize(controller);
				
				// Init form with the first selection
				this._initForm(controller, targets[0].getParameters().id);
				this._box.show();
			}
		},
	
		/**
		 * Initialize the form with values provided by the server
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button controller
		 */
		_delayedInitialize: function (controller)
		{
			if (this._initialized)
			{
				return;
			}
			
			this._form = Ext.create('Ext.form.Panel', {
				labelWidth: 120,
				border: false,
				
				defaultType :'datefield',
				
				defaults: {
					cls: 'ametys',
					labelWidth: 100,
					labelAlign: 'right',
					labelSeparator: '',
					msgTarget: 'side'
				},
				
				scrollable: true,
				
				items: [ 
						{
							name: 'startDate',
							itemId: 'startDate',
				        	fieldLabel: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_START_DATE}}",
					        ametysDescription: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_START_DATE_DESC}}"
				        },
				        {
				        	name: 'endDate',
				        	fieldLabel: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_END_DATE}}",
					        ametysDescription: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_END_DATE_DESC}}"
				        }
				]
			});
	
			this._box = Ext.create('Ametys.window.DialogBox',  {
				
				title : "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_DIALOG_TITLE}}",
				iconCls : "ametysicon-time33",
				
				width: 430,
				layout: 'form',
	
				items : [{
							xtype: 'container',
							cls: 'a-text',
							html: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_HINT}}",
						  },
						  this._form 
				],
				
				defaultFocus: 'startDate',
				closeAction: 'hide',
				
				referenceHolder: true,
				defaultButton: 'validate',
				
				buttons : [{
					reference: 'validate',
					text: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_DIALOG_OK_BTN}}",
					handler: Ext.bind(this._ok, this, [controller], false)
				}, {
					text: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_DIALOG_CANCEL_BTN}}",
					handler: Ext.bind(this._cancel, this)
				} ]
			});
			
			this._initialized = true;
		},
	
		/**
		 * @private
		 * Initialize the form with values provided by the server
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button controller
		 * @param {String} surveyId the id of the survey
		 */
		_initForm: function (controller, surveyId)
		{
			controller.serverCall('getScheduledDates',
					[surveyId], 
					Ext.bind(this._initFormCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_ERROR}}", 
							category: this.self.getName() 
						},
                        refreshing: true
					}
			);
		},
		
		/**
		 * @private
		 * Callback for the form initialization process
		 * @param {Object} response the server's response
		 * @param {String} [response.startDate] the scheduled starting date
		 * @param {String} [response.endDate] the scheduled ending date
		 * @param {Object} args the callback arguments
		 */
		_initFormCb: function(response, args)
		{
			var startDate = response.startDate;
			var endDate = response.endDate;
	
			var form = this._form.getForm();
			form.findField('startDate').setValue(!Ext.isEmpty(startDate) ? Ext.Date.parse(startDate, Ext.Date.patterns.ISO8601DateTime) : '');
			form.findField('endDate').setValue(!Ext.isEmpty(endDate) ? Ext.Date.parse(endDate, Ext.Date.patterns.ISO8601DateTime) : '');
			
			form.clearInvalid();
		},
	
		/**
		 * @private
		 * Saving process
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button controller
		 */
		_ok: function (controller)
		{
			var form = this._form.getForm();
			if (!form.isValid())
			{
				return;
			}
			
			var startDate = form.findField('startDate').getValue();
			var endDate = form.findField('endDate').getValue();
			
			// Check date consistency
			if (!Ext.isEmpty(endDate) && !Ext.isEmpty(startDate) && endDate.getTime() - startDate.getTime() <= 0)
			{
				form.findField('endDate').markInvalid ("{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_INTERVAL_ERROR}}");
				return;
			}
			
			var ids = [];
			var targets = controller.getAllRightSurveyTargets();
			for (var i=0; i < targets.length; i++)
			{
				ids.push(targets[i].getParameters().id);
			}
			
			var startDate = !Ext.isEmpty(startDate) ? Ext.Date.format(startDate, Ext.Date.patterns.ISO8601DateTime) : null;
			var endDate = !Ext.isEmpty(endDate) ? Ext.Date.format(endDate, Ext.Date.patterns.ISO8601DateTime) : null;
				
			controller.serverCall('setScheduledDate',
					[ids, startDate, endDate], 
					Ext.bind(this._setScheduledDateCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_SURVEY_OPENING_SCHEDULE_ERROR}}", 
							category: this.self.getName() 
						},
						arguments: {
							surveyIds: ids
						},
                        refreshing: true
					}
			);
		},
	
		/**
		 * @private
		 * Callback function after setting scheduled dates
		 * @param {Object} response the server's response
		 * @param {Object} args the callback arguments
		 */
		_setScheduledDateCb: function (response, args)
		{
			this._box.hide();
			
			var targets = [];
			Ext.Array.each(args.surveyIds, function (surveyId) {
				targets.push({
					id: Ametys.message.MessageTarget.SURVEY,
					parameters: {
						id: surveyId
					}
				});
			});
			
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.MODIFIED,
				parameters: {major: false},
				targets: targets
			});
		},
		
		/**
		 * @private
		 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
		 */
		_cancel: function ()
		{
			this._box.hide();
		}
	}
);