/*
 *  Copyright 2019 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.testSending.TestSendingActions', {
    singleton: true,
    
    /**
     * @private
     * @property {Ametys.window.DialogBox} _dialog The dialog box for sending a test newsletter.
     */
    
    /**
     * Send a newsletter to a specifiec email for testing purpose
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    sendTest: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        
        if (target == null)
        {
            return;
        }
        
        var newsletterId = target.getParameters().id;
        var title = target.getParameters().title;
        
        if (this._dialog == null)
        {
            this._dialog = this._createDialogBox(controller);
        }

        this._dialog.show();
        this._initForm(newsletterId, title);
    },
    
    /**
     * Create the dialog box for sending a newsletter.
     * @return {Ametys.window.DialogBox} The dialog box to input the recipient email
     * @private
     */
    _createDialogBox: 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',
                   id: 'inputRecipientHint',
                   html: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_HINT}}",
                   cls: 'text'
               },
               {
                   xtype: 'hidden',
                   name: 'newsletterId',
                   value: ''
               },
               {
                   xtype: 'textfield',
                   id: 'recipient',
                   name: 'recipient',
                   fieldLabel: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_RECIPIENT_LABEL}}",
                   ametysDescription: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_RECIPIENT_DESC}}",
                   allowBlank: false,
                   emptyText: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_RECIPIENT_EMPTY_TEXT}}"
               }
           ]
        });
        
        var dialog = Ext.create('Ametys.window.DialogBox', {
            layout: 'fit',
            
            title: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_TITLE}}",
            iconCls: 'ametysicon-desktop-opened29',
            
            width: 480,
            scrollable: false,
            
            items: [formPanel],
            
            closeAction: 'hide',
            buttons: [{
                text: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_BUTTON_OK}}",
                handler: Ext.bind(this._ok, this, [controller], false)
            }, {
                text: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_BUTTON_CANCEL}}",
                handler: Ext.bind(this._cancel, this),
                
            }]
        });
        
        return dialog;
    },
    
    /**
     * Initializes the form.
     * @param {String} newsletterId The id of the newsletter
     * @param {String} title The title of the newsletter
     * @private
     */
    _initForm: function(newsletterId, title)
    {
        var user = Ametys.getAppParameter('user');
        var form = this._dialog.items.getAt(0).getForm();
        form.reset();
        this._dialog.down('#inputRecipientHint').setHtml("{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_DIALOG_HINT}}".replace('{title}', title));
        form.findField('newsletterId').setValue(newsletterId);
        form.findField('recipient').setValue(user ? user.email || '' : '');
    },
    
    /**
     * The action to perform when the user clicks on the OK button from the dialog box.
     * @private
     */
    _ok: function()
    {
        var form = this._dialog.items.getAt(0).getForm();

        var params = form.getValues();
            
        if (form.isValid())
        {
            Ametys.data.ServerComm.callMethod({
				role: "org.ametys.plugins.newsletter.NewsletterDAO",
				methodName: "sendTestNewsletter",
				parameters: [params.newsletterId, params.recipient],
				callback: {
					scope: this,
					handler: this._callback
				},
				errorMessage: {
					category: this.self.getName(),
					msg: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_ERROR}}"
				},
				waitMessage: true
			});
        }
    },
    
    /**
     * The callback that will be invoked after a server response
     * @param {Ext.form.action.Action} response The server response.
     * @private
     */
    _callback: function(response)
    {
        if (response == true)
        {
            Ametys.Msg.show({
            title: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_SUCCESS_TITLE}}",
            msg: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_SUCCESS_MESSAGE}}",
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.INFO
            });
        
            this._dialog.hide();
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_ERROR_TITLE}}",
                msg: "{{i18n PLUGINS_NEWSLETTER_SEND_TO_RECIPIENT_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    },

    /**
     * @private
     * Callback on the cancel button
     */
    _cancel: function()
    {
        this._dialog.hide();
    }
});