/*
 *  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.
 */
/**
 * This class is a singleton to refuse a UGC content
 */
Ext.define('Ametys.plugins.ugc.RefuseUGCContentAction', {
    singleton: true,
    
    /**
     * @private
     * @property {Boolean} _initialized Indicates if the dialog box has been initialized
     */
    
    /**
     * @private
     * @property {Ext.form.Panel} _formPanel The form panel
     */
    
    /**
     * @private
     * @property {Ametys.window.DialogBox} _box The dialog box
     */
    
    /**
     * Opens the dialog box to accept and choose transformation options for UGC content
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    act: function(controller)
    {
    	this.open(controller.getInitialConfig(), controller);
    },
    
    /**
     * Open the dialog box to select options for UGC content transformation
     * @param {Object} config The initial configuration
     *  @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    open: function(config, controller)
    {
        if (!this._initialized)
        {
            this._formPanel = this._createFormPanel(config);
            
            this._box = Ext.create('Ametys.window.DialogBox', {
                title: config.dialogTitle || "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_DIALOG_LABEL}}",
                iconCls: config.dialogIconCls || "ametysicon-body-people-think decorator-ametysicon-sign-cross-black",
                
                bodyStyle: {
                    padding: '10px'
                },
                width: 500,
                scrollable: false,
                closeAction: 'method-hide',
                
                items: [ this._formPanel ],
                
                selectDefaultFocus: true,
                
                referenceHolder: true,
                defaultButton: 'validate',

                closeAction: 'hide',
                
                buttons: [{
                    reference: 'validate',
                    text: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_DIALOG_OK_BTN}}",
                    handler: Ext.bind(this._validate, this, [config, controller], false)
                }, {
                    text: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_DIALOG_CANCEL_BTN}}",
                    handler: Ext.bind(this._closeBox, this)
                }]    
            });
        }
        
        this._initForm();
        this._box.show();
    },
    
    /**
     * @private
     * Create the form panel.
     * @param {Object} config The initial configuration
     */
    _createFormPanel: function(config)
    {
        return Ext.create('Ext.form.Panel', {
            scrollable: true,
            flex: 1,
            border: false,
            
            bodyStyle: {
                padding: '5px'
            },
            
            defaults: {
                cls: 'ametys',
                labelWidth: 120,
                width: '100%',
                labelAlign: 'top',
                labelSeparator: '',
                msgTarget: 'side'
            },
            
            items: [
                {
                    xtype: 'component',
                    cls: 'a-text',
                    html: config.dialogHintMessage || "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_DIALOG_HINT}}",
                    style: {
                        marginBottom: '5px'
                    }
                }, 
                {
                    xtype: 'checkboxfield',
                    name: 'withNotification',
                    boxLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_NOTIFY_LABEL}}",
                    checked: true,
                    inputValue: 'true'
                },
                {
                    xtype: 'textarea',
                    name: 'comment',
                    height: 150,
                    fieldLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_COMMENT_LABEL}}",
                    labelStyle: "margin-bottom: 5px;"
                } 
            ]
        });
    },
    
    /**
     * @private
     * Initialize the form
     */
    _initForm: function()
    {
        var form = this._formPanel.getForm();
        form.findField('comment').setValue('');
        form.findField('withNotification').setValue(true);
    },
    
    /**
    * @private
    * Handler for the 'ok' button of the dialog box
    * @param {Ametys.ribbon.element.ui.ButtonController} [controller] The controller calling this function
    */
    _validate: function(config, controller)
    {
        var form = this._formPanel.getForm();
        
        var values = form.getValues();
        
        this._refuseUGCContent(controller, controller.getContentIds(), values.comment, values.withNotification == 'true');
    },

    /**
     * @private
     * Accept UGC content
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @param {String[]} contentIds The id of UGC contents
     * @param {String} comment the reject comment
     */
    _refuseUGCContent: function(controller, contentIds, comment, withNotification)
    {
        controller.serverCall(
                'refuseUGCContent', 
                [contentIds, comment, withNotification], 
                Ext.bind(this._refuseUGCContentCb, this), 
                {
                    waitMessage: this._box, 
                    errorMessage: true, 
                    arguments: {controller: controller}
                }
        );
    },
    
    /**
     * @private
     * Callback function invoked after UGC content acceptation
     * @param {Object} response The server response
     * @param {Object} args The arguments
     */
    _refuseUGCContentCb: function(response, args)
    {
        if (!response.success)
        {
            Ext.Msg.show({
                title: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_ERROR_TITLE}}",
                msg: "{{i18n PLUGINS_UGC_HELPER_CONTENT_REFUSE_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
    
        }
        else
        {
            // Fire UGC content(s) deletion
            var deletedTargets = [];
            Ext.Array.each(args.controller.getMatchingTargets() || [], function(target) {
                if (Ext.Array.contains(response.deletedContents, target.getParameters().id))
                {
                    deletedTargets.push(target);   
                }
            });
            
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.DELETED,
                targets: deletedTargets
            });
                
            this._box.close();
        }
    },
    
    /**
     * @private
     * Callback for the "cancel" button of the dialog. Close the dialog.
     */
    _closeBox: function()
    {
    	if (this._box)
    	{
    		this._box.close();
    	}
    }
});