/*
 *  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 holds the methods to notify the publication of a page
 */
Ext.define('Ametys.plugins.web.page.NotifyPublication', {

		singleton: true,
		
		/**
		 * @private
		 * @property {Ametys.window.DialogBox} _box The dialog box
		 */
		
		/**
		 * @private
		 * @property {Ext.form.Panel} _form the form panel for users and groups 
		 */
		
		/**
		 * Notify 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);
				
				this._initForm();
				this._box.show();
			}
		},
		
        /**
         * @private
         * Initialize the form
         */
		_initForm: function ()
		{
			var form = this._form.getForm();
			form.findField("users").setValue();
			form.findField("groups").setValue();
			form.findField("comment").setValue();
            
            form.clearInvalid();
		},
		
		/**
		 * Initialize the notification dialog box
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button's controller
		 */
		_delayedInitialize: function(controller)
		{
			if (!this._box)
			{
				this._form = Ext.create('Ext.form.Panel', {
					border: false,
					scrollable: true,
					
					defaults: {
						cls: 'ametys',
						labelWidth: 80,
						labelSeparator: '',
						msgTarget: 'side',
						width: 400
					},
					
					items: [{
								xtype: 'component',
								cls: 'a-text',
								html: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_HINT}}"
							},
					        {
								xtype: 'edition.user',
								name: 'users',
								itemId: 'users',
								fieldLabel: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_USERS}}",
								multiple: true
							},
							{
								xtype: 'edition.group',
								name: 'groups',
								fieldLabel: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_GROUPS}}",
								multiple: true
							},
							{
								xtype: 'component',
								cls: 'a-text',
								html: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_COMMENT_HINT}}"
							},
							{
								 xtype : 'edition.textarea',
								 name: 'comment',
								 hideLabel: true,
								 maxLength: 400,
								 height: 140
							},
							{
								xtype: 'component',
								cls: 'a-text',
								html: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_HINT_2}}"
							}
					]
				});
		
				this._box = new Ametys.window.DialogBox ({
					title: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_TITLE}}",
					iconCls: 'ametysicon-world91 decorator-ametysicon-paper11',
			
					layout: 'fit',
					width: 450,
					maxHeight: 500,
					
					items: [this._form],
						
					defaultFocus: 'users',
					
					referenceHolder: true,
					defaultButton: 'validate',
					
					closeAction: 'hide',
					buttons : [{
						reference: 'validate',
						text : "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_BTN_OK}}",
						handler: Ext.bind(this._sendNotification, this, [controller], false)
				    }, 
				    {
						text : "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_DIALOG_BTN_CANCEL}}",
						handler: function () {this._box.hide();},
                        scope: this
				    }]
				});
			}
		},
		
		/**
		 * @private
		 * Actual notification sending process through a server call
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller the button's controller
		 */
		_sendNotification: function (controller)
		{
			var form = this._form.getForm();
			if (!form.isValid())
			{
				return;
			}
			
			var ids = [];
			var targets = controller.getAllRightPageTargets();
			for (var i=0; i < targets.length; i++)
			{
				ids.push(targets[i].getParameters().id);
			}
			
			var users = form.findField('users').getValue();
			var groups = form.findField('groups').getValue();
			var comment = form.findField('comment').getValue();
			
			controller.serverCall('sendOnlineNotification',
					[ids, !Ext.isEmpty(users) ? users : [], !Ext.isEmpty(groups) ? groups : [], comment], 
					Ext.bind(this._sendOnlineNotificationCb, this),
					{ 
						errorMessage: { 
							msg: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_ERROR}}", 
							category: this.self.getName() 
						},
                        refreshing: true
					}
			);
		},

		/**
		 * @private
		 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
		 */
		_sendOnlineNotificationCb: function (response)
		{
			this._box.hide();
            
            var noRightPages = response["noright-pages"] || [];
            if (noRightPages.length)
            {
                var msg = "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_NORIGHT_ERROR}}";
                msg += Ext.Array.map(noRightPages, p => p.title).join(", ");
                
                Ametys.Msg.show({
                    title: "{{i18n PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_LABEL}}",
                    msg: msg,
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
		}
	}
);