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

/**
 * Singleton class to handle actions on subscribers for a category.
 * @private
 */
 Ext.define('Ametys.plugins.newsletter.subscribers.SubscribersActions', {
 	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _dialog The dialog box for importing subscribers.
 	 */
 	
 	/**
 	 * Exports a list of subscribers for a category to XLS format.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	exportXls: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		if (target == null)
 		{
 			return;
 		}
 		
 		var filename = target.getParameters().title;
 		var params = {
 			categoryID: target.getParameters().id,
 			siteName: target.getParameters().siteName,
 			filename: filename
 		}
		var url = Ametys.getPluginDirectPrefix(controller.getPluginName()) + '/subscribers/' + encodeURIComponent(filename) + ".xls";
		
		Ametys.openWindow (url, params, 'GET');
 	},
 	
 	/**
 	 * Imports a list of subscribers for a category from CSV format.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	importCsv: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		if (target == null)
 		{
 			return;
 		}
 		
 		var categoryId = target.getParameters().id;
 		
 		if (this._dialog == null)
 		{
 			this._dialog = this._createDialogBox();
 		}
 		this._dialog.show();
 		this._initForm(categoryId);
 	},
 	
 	/**
 	 * Create the dialog box for importing subscribers.
 	 * @return {Ametys.window.DialogBox} The importing dialog box
 	 * @private
 	 */
 	_createDialogBox: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
 			border: false,
	        
	        scrollable: false,
	        
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 60,
	        	anchor: '90%'
	        },
	        items: [
		        {
		        	xtype: 'component',
		        	id: 'importCsvHint',
	                html: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_HINT}}",
	                cls: 'text'
		        },
		        {
		        	xtype: 'hidden',
		        	name: 'categoryId',
		        	value: ''
		        },
		        {
		        	xtype: 'fileuploadfield',
		        	id: 'importFile',
                	name: 'importFile',
		        	fieldLabel: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_FILE_LABEL}}",
                	ametysDescription: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_FILE_DESC}}",
                	allowBlank: false,
                	emptyText: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_FILE_EMPTY_TEXT}}",
                	buttonText: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_FILE_BUTTON}}"
		        },
		        {
		        	xtype: 'checkbox',
		        	name: 'cleanSubscribers',
		        	inputValue: 'true',
		        	hideLabel: true,
		        	style: {
		                marginLeft: '60px'
		            },
		        	boxLabel: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_CLEAN_SUBSCRIBERS}}",
	                ametysDescription: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_CLEAN_SUBSCRIBERS_DESC}}",
		        	checked: false
		        }
	        ]
 		});
 		
 		var dialog = Ext.create('Ametys.window.DialogBox', {
 			layout: 'fit',
 			
 			title: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_TITLE}}",
 			iconCls: 'ametysicon-file-extension-csv decorator-ametysicon-upload119',
 			
 			width: 480,
 			scrollable: false,
 			
 			items: [formPanel],
 			
 			closeAction: 'hide',
 			buttons: [{
 				text: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_BUTTON_OK}}",
 				handler: Ext.bind(this._ok, this)
 			}, {
 				text: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_BUTTON_CANCEL}}",
 				handler: Ext.bind(this._cancel, this)
 			}]
 		});
 		
 		return dialog;
 	},
 	
 	/**
 	 * Initializes the form.
 	 * @param {String} categoryId The id of the category
 	 * @private
 	 */
 	_initForm: function(categoryId)
 	{
 		var form = this._dialog.items.getAt(0).getForm();
 		form.findField('categoryId').setValue(categoryId);
	    form.findField('importFile').reset();
	    form.findField('cleanSubscribers').setValue(false);
 	},
 	
 	/**
 	 * The action to perform when the user clicks on the OK button from the importing dialog box.
 	 * @param {Ext.button.Button} button The clicked button.
 	 * @param {Ext.event.Event} event The click event.
 	 * @private
 	 */
 	_ok: function(button, event)
 	{
 		var form = this._dialog.items.getAt(0).getForm();
 		var clean = form.findField('cleanSubscribers').checked;
 		
 		if (clean)
 		{
 			Ametys.Msg.confirm("{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_WAIT_TITLE}}",
 					"{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_CLEAN_CONFIRM}}",
 					function(answer) {
 						if (answer == 'yes')
 						{
 							this._doImport();
 						}
 					},
 					this
 			);
 		}
 		else
 		{
 			this._doImport();
 		}
 	},
 	
 	/**
 	 * The action to perform when the user clicks on the cancel button from the importing dialog box.
 	 * @param {Ext.button.Button} button The clicked button.
 	 * @param {Ext.event.Event} event The click event.
 	 * @private
 	 */
 	_cancel: function(button, event)
 	{
 		this._dialog.hide();
 	},
 	
 	/**
 	 * The action to perform when the user confirmed the import.
 	 * @private
 	 */
 	_doImport: function()
 	{
 		var form = this._dialog.items.getAt(0).getForm();
 		
 		if (form.isValid())
 		{
 			form.submit({
 				url: Ametys.getPluginDirectPrefix('newsletter') + '/subscribers/import',
 				params: {siteName: Ametys.getAppParameter('siteName')},
 				
 				waitTitle: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_WAIT_TITLE}}",
 				waitmsg: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_DIALOG_WAIT_MSG}}",
 				
 				success: Ext.bind(this._success, this),
 				failure: Ext.bind(this._failure, this),
 			});
 		}
 	},
 	
 	/**
 	 * The callback that will be invoked after a successful response
 	 * @param {Ext.form.Basic} form The form that requested the action.
 	 * @param {Ext.form.action.Action} action The Action object which performed the operation.
 	 * @private
 	 */
 	_success: function(form, action)
 	{
 		var message = "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_SUCCESS_START}}";
	    
	    if (action.result.subscribedCount > 0)
	    {
	        message = message + action.result.subscribedCount + "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_SUCCESS_SUBSCRIBED}}";
	    }
	    
	    if (action.result.existingCount > 0)
	    {
	        message = message + action.result.existingCount + "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_SUCCESS_EXISTING}}";
	    }
	    
	    if (action.result.errorCount > 0)
	    {
	        message = message + action.result.errorCount + "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_SUCCESS_ERROR}}";
	    }
	    
	    Ametys.Msg.show({
	        title: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_SUCCESS_TITLE}}",
	        msg: message,
	        buttons: Ext.Msg.OK,
	        icon: Ext.MessageBox.INFO
	    });
	    
	    this._dialog.hide();
	    
	    Ext.create("Ametys.message.Message", {
    		type: Ametys.message.Message.MODIFIED,
    		targets: {
    		    id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY,
    			parameters: {
    				ids: [action.result.categoryId]
    			}
    		}
    	});
 	},
 	
 	/**
 	 * The callback that will be invoked after a failed transaction attempt.
 	 * @param {Ext.form.Basic} form The form that requested the action.
 	 * @param {Ext.form.action.Action} action The Action object which performed the operation.
 	 * @private
 	 */
 	_failure: function(form, action)
 	{
 		var message = '';
	    var error = action.result.error;
	    
	    if (error == 'unknown-category')
	    {
	        message = "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_ERROR_UNKNOWN_CATEGORY}}";
	    }
	    else if (error == 'invalid-extension')
	    {
	        message = "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_ERROR_INVALID_FILE}}";
	    }
	    else if (error == 'rejected-file')
	    {
	        message = "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_ERROR_REJECTED_FILE}}";
	    }
	    else
	    {
	    	message = "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_ERROR}}";
	    }
	    
	    Ametys.Msg.show({
	        title: "{{i18n PLUGINS_NEWSLETTER_IMPORT_CSV_ERROR_TITLE}}",
	        msg: message,
	        buttons: Ext.Msg.OK,
	        icon: Ext.MessageBox.ERROR
	    });
 	},
 	
 	/**
     * Allow the user to add new subscribers for the newsletter.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
 	addSubscribers: function(controller)
 	{
        var target = controller.getMatchingTargets()[0];
        
        if (target == null)
        {
            return;
        }
 	    
 	    var categoryId = target.getParameters().id;
 	    
 	    this._pluginName = controller.getPluginName();
 	    
 	    if (this._dialogAdd == null)
 	    {
 	        this._dialogAdd = this._createDialogBoxAdd(controller);
 	    }
 	    
 	    this._dialogAdd.show();
 	    this._initFormAdd (categoryId);
 	},

    /**
     * @private
     * Initialize the form with category info
     * @param {String} categoryId The category id
     */
 	_initFormAdd: function (categoryId)
 	{
 	    var form = this._dialogAdd.items.getAt(0).getForm();
 	    form.findField('categoryId').setValue(categoryId);
 	    form.findField('emailsList').reset();
 	},

    /**
     * @private
     * Create the dialog box to add
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @return {Ametys.window.DialogBox} The dialog box
     */
 	_createDialogBoxAdd: function(controller)
 	{
 	    var formPanel = Ext.create('Ext.form.Panel', {
           border: false,
           
           scrollable: false,
           
           defaults: {
               cls: 'ametys',
               labelSeparator: '',
               labelAlign: 'right',
               labelWidth: 60,
               anchor: '90%'
           },
           items: [
               {
                   xtype: 'component',
                   html: "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_DIALOG_HINT}}",
                   cls: 'text'
               },
               {
                   xtype: 'hidden',
                   name: 'categoryId',
                   value: ''
               },
               {
                   xtype:'textarea',
                   id: 'emailsList',
                   name: 'emailsList',
                   hideLabel: true,
                   height: 60
               }
           ]
        });
        
        var dialog = Ext.create('Ametys.window.DialogBox', {
            layout: 'fit',
            
            title: "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_DIALOG_TITLE}}",
            iconCls: 'ametysicon-black302 decorator-ametysicon-add64',
            
            width: 480,
            scrollable: false,
            
            items: [formPanel],
            
            defaultFocus: 'emailsList',
            closeAction: 'hide',
            
            buttons: [{
                text: "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_DIALOG_BUTTON_OK}}",
                handler: Ext.bind(this._okAdd, this, [controller], false)
            }, {
                text: "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_DIALOG_BUTTON_CANCEL}}",
                handler: Ext.bind(this._cancelAdd, this)
            }]
        });
 	    
 	    return dialog;
 	},

    /**
     * @private
     * Callback of the add button
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
 	_okAdd: function(controller)
 	{
 	    var form = this._dialogAdd.items.getAt(0).getForm();
 	    
 	    if (form.isValid())
 	    {
 	        var params = form.getValues();
 	        
 	       controller.serverCall ('addSubscribers', 
 	                         [Ametys.getAppParameter('siteName'), params.categoryId, params.emailsList], 
 	                         Ext.bind (this.callbackAdd, this), 
 	                         { errorMessage: true, refreshing: true });
 	    }
 	},

        /**
     * @private
     * Callback of the cancel button
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
 	_cancelAdd: function(controller)
 	{
 	    this._dialogAdd.hide();
 	},

    /**
     * @private
     * Callback when the subscribers were added
     * @param {Object} response The server response
     */
 	callbackAdd: function(response)
    {
        var message = '';
        var messageTitle = '';

        if (response.success == "true")
        {
            message += "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_SUCCESS_START}}";
            
            message += response.subscribedCount + "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_SUCCESS_SUBSCRIBED}}";
            
            if (response.existingCount > 0)
            {
                message += response.existingCount + "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_SUCCESS_EXISTING}}";
            }
            
            if (response.errorCount > 0)
            {
                message += response.errorCount + "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_SUCCESS_ERROR}}";
            }
            
            messageTitle = "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_SUCCESS_TITLE}}";
        }
        else
        {
            if (response.error == 'unknown-category')
            {
                message += "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_ERROR_UNKNOWN_CATEGORY}}";
            }
            else
            {
                message += "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_ERROR}}";
            }
            
            messageTitle = "{{i18n PLUGINS_NEWSLETTER_ADD_SUBSCRIBERS_ERROR_TITLE}}";
        }

        Ametys.Msg.show({
            title: messageTitle,
            msg: message,
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.INFO
        });

        if (response.success == "true")
        {
            this._dialogAdd.hide();
            
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY,
                    parameters: {
                        ids: [response.categoryId]
                    }
                }
            });
        }
    },

 	/* ------------------------------------ */
 	/* ------------------------------------ */
 	/* ------------------------------------ */
 	/**
 	 * Remove subscribers from a category
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
 	 */
    removeSubscribers: function (controller)
 	{
 	   var targets = controller.getMatchingTargets();
       if (targets.length > 0)
       {
           Ametys.Msg.confirm("{{i18n PLUGINS_NEWSLETTER_HANDLE_REMOVE_SUBSCRIBERS}}", 
                   "{{i18n PLUGINS_NEWSLETTER_HANDLE_REMOVE_SUBSCRIBERS_CONFIRM}}", 
                   Ext.bind(this._doRemoveAction, this, [targets, controller], 1), 
                   this
           );
       }
 	},

    /**
     * @private
     * Really remove subscribers
     * @param {String} button The pressed button in the dialogbox. Can be 'yes'.
     * @param {Ametys.message.MessageTarget[]} targets The message targets of the selection message
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
 	_doRemoveAction: function(button, targets, controller)
 	{
 	    if (button == 'yes')
 	    {
 	        var target = targets[0];
 	        
 	        if (target == null)
 	            return; 
 	        
 	        var emails = [];
 	        for (var i=0; target.getSubtargets().length > i; i++)
 	        {
 	            emails.push(target.getSubtargets()[i].getParameters().email);
 	        }
 	        
 	       controller.serverCall ('removeSubscribers', 
               [Ametys.getAppParameter('siteName'), target.getParameters().id, emails], 
               Ext.bind (this.callbackRemove, this, [target], 1), 
               { errorMessage: true, refreshing: true });
 	    }
 	},

    /**
     * @private
     * The callback when the selection was removed from the server
     * @param {Object} response The server response
     * @param {Ametys.message.MessageTarget[]} targets The message targets of the selection message
     */
 	callbackRemove: function (response, targets)
 	{
 	    var msg = response.message != null ? response.message : '';
 	    if (msg == "unknown-category")
 	    {
 	        Ametys.Msg.show({
 	            title: "{{i18n PLUGINS_NEWSLETTER_HANDLE_REMOVE_SUBSCRIBERS_ERROR}}",
 	            msg: "{{i18n PLUGINS_NEWSLETTER_HANDLE_REMOVE_SUBSCRIBERS_UNKNOWN_CATEGORY}}",
 	            buttons: Ext.Msg.OK,
 	            icon: Ext.MessageBox.ERROR
 	        });
 	        return;
 	    }
 	    
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.MODIFIED,
            targets: targets
        });
 	}
});