/*
 *  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 transform a UGC content
 */
Ext.define('Ametys.plugins.ugc.AcceptUGCContentAction', {
    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)
    {
        Ext.applyIf(config, {
            workflowName: 'content',
            initActionId: 1
        });
        
        if (!this._initialized)
        {
            this._formPanel = this._createFormPanel(config);
            
            this._box = Ext.create('Ametys.window.DialogBox', {
                title: config.dialogTitle || "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_DIALOG_LABEL}}",
                iconCls: config.dialogIconCls || "ametysicon-body-people-think decorator-ametysicon-check34",
                
                bodyStyle: {
                    padding: '10px'
                },
                width: 550,
                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_ACCEPT_DIALOG_OK_BTN}}",
                    handler: Ext.bind(this._validate, this, [config, controller], false)
                }, {
                    text: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_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: '10px'
            },
            
            defaults: {
                cls: 'ametys',
                labelWidth: 120,
                width: '100%',
                labelAlign: 'right',
                labelSeparator: '',
                msgTarget: 'side'
            },
            
            items: [
                {
                    xtype: 'component',
                    cls: 'a-text',
                    html: config.dialogHintMessage1 || "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_CONTENT_TYPE_HINT}}",
                    style: {
                        marginBottom: '5px'
                    }
                }, 
                {
                    xtype: 'edition.select-content-types',
                    fieldLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_CONTENT_TYPE}}",
                    ametysDescription: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_CONTENT_TYPE_DESC}}",
                    name: 'content-type',
                    allowBlank: false,
                    excludePrivate: true,
                    excludeMixin: true,
                    excludeAbstract: true,
                    excludeReferenceTable: true
                },
                {
                    xtype: 'component',
                    cls: 'a-text',
                    html: config.dialogHintMessage2 || "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_HINT}}",
                    style: {
                        marginBottom: '5px',
                        marginTop: '10px'
                    }
                }, 
                {
                    xtype: 'radiofield',
                    boxLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_NEW}}",
                    name: 'page-mode',
                    itemId: 'page-mode-new',
                    inputValue: 'new',
                    checked: true,
                    listeners: {
                        'change': {
                            scope: this,
                            fn: function(fd, checked) {
                                this._formPanel.getForm().findField('parent-page').setDisabled(!checked);
                                this._formPanel.getForm().findField('page').clearInvalid();
                            }
                        }
                    }
                },
                {
                    xtype: 'edition.select-page',
                    siteContext: Ametys.web.form.widget.SelectPage.SITE_CONTEXT_CURRENT,
                    sitemapContext: Ametys.web.form.widget.SelectPage.SITEMAP_CONTEXT_CURRENT,
                    name: 'parent-page',
                    fieldLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_NEW_PAGE}}",
                    ametysDescription: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_NEW_PAGE_DESC}}",
                    allowCreation: false
                },
                {
                    xtype: 'radiofield',
                    boxLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_AFFECT}}",
                    name: 'page-mode',
                    itemId: 'page-mode-affect',
                    inputValue: 'affect',
                    listeners: {
                        'change': {
                            scope: this,
                            fn: function(fd, checked) {
                                this._formPanel.getForm().findField('page').setDisabled(!checked);
                            }
                        }
                    }
                },
                {
                    xtype: 'edition.select-page',
                    siteContext: Ametys.web.form.widget.SelectPage.SITE_CONTEXT_CURRENT,
                    sitemapContext: Ametys.web.form.widget.SelectPage.SITEMAP_CONTEXT_CURRENT,
                    name: 'page',
                    fieldLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_AFFECT_PAGE}}",
                    ametysDescription: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_AFFECT_PAGE_DESC}}",
                    allowCreation: false,
                    disabled: true
                },
                {
                    xtype: 'radiofield',
                    boxLabel: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_NONE}}",
                    name: 'page-mode',
                    itemId: 'page-mode-none',
                    inputValue: 'none',
                    listeners: {
                        'change': {
                            scope: this,
                            fn: function(fd, checked) {
                                this._formPanel.getForm().findField('page').clearInvalid();
                            }
                        }
                    }
                }
                
            ]
        });
    },
    
    /**
     * @private
     * Initialize the form
     */
    _initForm: function()
    {
        var form = this._formPanel.getForm();
        
        form.findField('page-mode').setValue('new');
	    form.findField('parent-page').setValue('');
	    form.findField('page').setValue('');
	    form.findField('page').clearInvalid();
    },
    
    /**
    * @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();
        if (!form.isValid())
        {
            return;
        }
        
        var values = form.getValues();
        
        var page = null;
        var mode = values['page-mode'];
        if (mode == 'new')
        {
            page = values['parent-page'];
        }
        else if (mode == 'affect')
        {
            page = values['page'];
            if (page == '')
	        {
	            form.findField('page').markInvalid("{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_PAGE_MODE_AFFECT_PAGE_EMPTY}}");
	            return;
	        }
        }
        
        this._acceptUGCContent(controller, controller.getContentIds(), values['content-type'], config.workflowName, config.initActionId, mode, page);
    },

    /**
     * @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 {Object} cTypeId The target content type. Can be empty.
     * @param {String} workflowName the workflow name
     * @param {Number} initActionId The id of initial workflow action for created contents
     * @param {Object} mode The insertion mode (new, affect or none)
     * @param {Object} page the page id. Can be empty for 'none' mode.
     */
    _acceptUGCContent: function(controller, contentIds, cTypeId, workflowName, initActionId, mode, page)
    {
        controller.serverCall(
                'acceptUGCContent', 
                [contentIds, cTypeId, workflowName, initActionId, mode, page],
                Ext.bind(this._acceptUGCContentCb, this), 
                {
                    waitMessage: this._box, 
                    errorMessage: true, 
                    arguments: {controller: controller, mode: mode, page: page}
                }
        );
    },
    
    /**
     * @private
     * Callback function invoked after UGC content acceptation
     * @param {Object} response The server response
     * @param {Object} args The arguments
     */
    _acceptUGCContentCb: function(response, args)
    {
        if (!response.success)
        {
            if (response.error == 'invalid-page')
            {
                Ext.Msg.show({
                    title: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_INVALID_PAGE_TITLE}}",
                    msg: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_INVALID_PAGE_ERROR}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
                return;
            }
            
            if (response.error == 'invalid-content-type')
            {
                Ext.Msg.show({
                    title: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_INVALID_CONTENT_TYPE_TITLE}}",
                    msg: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_INVALID_CONTENT_TYPE_ERROR}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
                return;
            }
            
            Ext.Msg.show({
                title: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_ERROR_TITLE}}",
                msg: "{{i18n PLUGINS_UGC_HELPER_CONTENT_ACCEPT_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
    
        }
        else
        {
            if (args.mode == 'new')
            {
                var pageIds = Ext.Array.map(response.createdContents || [], function(content) {  
                    return content.pageId;
                });
                
                Ext.create("Ametys.message.Message", {
	                type: Ametys.message.Message.CREATED,
	                parameters: {major: true},
	                targets: {
	                    id: Ametys.message.MessageTarget.PAGE,
	                    parameters: {
	                        ids: pageIds
	                    }
	                }
	            });
                
                for (var i in pageIds)
                {
                    // Open created pages
	                Ametys.tool.ToolsManager.openTool ("uitool-page", {'id': pageIds[i]});
                }
            }
            else if (args.mode == 'affect')
            {
                Ext.create("Ametys.message.Message", {
                    type: Ametys.message.Message.MODIFIED,
                    parameters: {major: true},
                    targets: {
                        id: Ametys.message.MessageTarget.PAGE,
                        parameters: {
                            ids: [args.page]
                        }
                    }
                });
                
                // Open updated page
                Ametys.tool.ToolsManager.openTool ("uitool-page", {'id': args.page});
            }
            else
            {
                // Open contents
                Ext.Array.each(response.contents, function(content) {
                    Ametys.tool.ToolsManager.openTool ("uitool-content", {'id': content.id});
                });
            }
            
            // 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();
    	}
    }
});