/*
 *  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 publication of page
 */
Ext.define(
	'Ametys.plugins.web.page.SchedulePublication', 
	{
		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 publication of a page
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling this function
		 */
		act: function(controller)
		{
			var targets = controller.getAllRightPageTargets();
			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', {
				border: false,
				
				defaultType :'datetimefield',
				
				defaults: {
					cls: 'ametys',
					labelAlign: 'top',
					labelSeparator: '',
					msgTarget: 'side'
				},
				
				items: [ 
						{
							name: 'startDate',
				        	fieldLabel: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_START_DATE}}",
					        ametysDescription: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_START_DATE_DESC}}"
				        },
				        {
				        	name: 'endDate',
				        	fieldLabel: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_END_DATE}}",
					        ametysDescription: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_END_DATE_DESC}}"
				        },
						{
		                    xtype: 'component',
		                    cls: 'a-text',
		                    html: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_WARNING_TEXT}}"
		                }
				]
			});
	
			this._box = Ext.create('Ametys.window.DialogBox',  {
				
				title: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_TITLE}}",
				iconCls: 'ametysicon-time33',
				
				width: 430,
                bodyPadding: 20,
	
				items : [{
							xtype: 'component',
							cls: 'a-text',
							html: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_HINT}}",
                            margin: "0 0 10 0"
						  },
						  this._form 
				],
				
				defaultFocus: this._form.getForm().findField('startDate'),
				closeAction: 'hide',
				
				referenceHolder: true,
				defaultButton: 'validate',
								
				buttons : [
				{
                    itemId: 'remove',
                    text: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_REMOVE_BTN}}",
                    handler: Ext.bind(this._remove, this, [controller], false)
                },
                { xtype: 'tbspacer', flex: 1 },
				{
					reference: 'validate',
					text: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_OK_BTN}}",
					handler: Ext.bind(this._ok, this, [controller], false)
				}, {
					text: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_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} pageId the id of the page
		 */
		_initForm: function (controller, pageId)
		{
			controller.serverCall('getPublicationDates',
					[pageId], 
					Ext.bind(this._initFormCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_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 publication starting date
		 * @param {String} [response.endDate] the publication 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) : '');
			
			this._box.down('#remove').setDisabled(Ext.isEmpty(startDate) && Ext.isEmpty(endDate));
			
			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_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_INTERVAL_ERROR}}");
				return;
			}
			
			var ids = [];
			var targets = controller.getAllRightPageTargets();
			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('setPublicationDate',
					[ids, startDate, endDate], 
					Ext.bind(this._setPublicationDateCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_ERROR}}", 
							category: this.self.getName() 
						},
						arguments: {
							pageIds: ids
						},
                        refreshing: true
					}
			);
		},
		
		/**
		 * @private
		 * Process for removing acknowledgement of receipt 
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button controller
		 */
		_remove: function (controller)
		{
			var ids = [];
			var targets = controller.getAllRightPageTargets();
			for (var i=0; i < targets.length; i++)
			{
				ids.push(targets[i].getParameters().id);
			}
			
			controller.serverCall('setPublicationDate',
				[ids, null, null], 
				Ext.bind(this._setPublicationDateCb, this),
				{ 
					errorMessage: { 
						msg: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_DIALOG_ERROR}}", 
						category: this.self.getName() 
					},
					arguments: {
						pageIds: ids
					},
                    refreshing: true
				}
		);
		},
		
		/**
		 * @private
		 * Callback function after setting publication dates
		 * @param {Object} response the server's response
		 * @param {Object} args the callback arguments
		 */
		_setPublicationDateCb: function (response, args)
		{
			this._box.hide();
			
            var pageIds = response["allright-pages"] || [];
            if (pageIds.length)
            {
                Ext.create('Ametys.message.Message', {
	                type: Ametys.message.Message.MODIFIED,
	                parameters: {major: false},
	                targets: [{
	                    id: Ametys.message.MessageTarget.PAGE,
	                    parameters: {
	                        ids: pageIds
	                    }
	                }]
	            });
            }
            
            // Handle errors
            var errorMsg = "";
            var pagesInError = response["error-pages"] || []
            if (pagesInError.length)
            {
                errorMsg += "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_PAGE_ERROR}}";
                errorMsg += Ext.Array.map(pagesInError, p => "<strong>" + p.title + "</strong>").join(", ");
            }		
            
            var pagesLocked = response["locked-pages"] || []
            if (pagesLocked.length)
            {
                errorMsg += "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_LOCKED_ERROR}}";
                errorMsg += Ext.Array.map(pagesLocked, p => "<strong>" + p.title + "</strong>").join(", ");
            }		
            
            var noRightPages = response["noright-pages"] || [];
            if (noRightPages.length)
            {
                errorMsg += "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_NORIGHT_ERROR}}";
                errorMsg += Ext.Array.map(noRightPages, p => "<strong>" + p.title + "</strong>").join(", ");
            }   
            
            if (errorMsg)
            {
                Ametys.Msg.show({
                    title: "{{i18n PLUGINS_WEB_PAGE_SCHEDULE_PUBLICATION_LABEL}}",
                    msg: errorMsg,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
		},
		
		/**
		 * @private
		 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
		 */
		_cancel: function ()
		{
			this._box.hide();
		}
	}
);