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


/**
 * Show the values of contents in a dialog, and allow the inline modification of its attributes
 */
Ext.define('Ametys.cms.form.widget.SelectContent.EditContentsDialogBox', {
    singleton: true,
    
    /**
     * Open a dialogbox to edit the given contents in a grid
     * @param {String/String[]} contentsIds The content(s) identifier(s) to edit in a row
     * @param {String} contentType The content type common to all contents
     * @param {Function} callback The callback at the end of the edition
     * @param {Object[]} callback.contents The contents that were editable. Can be null if the user cancel the edition.
     * @param {String} callback.contents.id The content identifier
     * @param {String} callback.contents.title The content title
     * @param {Object} [options] The options
     * @param {String} options.view The attributes view to use. Default to the default edition view or main.
     * @param {String} options.title The dialogbox title
     * @param {String} options.workflowEditActionId See Ametys.cms.content.EditContentsGrid#cfg-workflowEditActionId
     * @param {String} options.messageTarget See Ametys.cms.content.EditContentsGrid#messageTarget
     */
    openDialog: function(contentsIds, contentType, callback, options)
    {
        var multiple = Ext.isArray(contentsIds);
        contentsIds = Ext.Array.from(contentsIds);
        options = options || {};

        var grid = Ext.create("Ametys.cms.content.EditContentsGrid", {
            border: false,
            
            allowEdition: true,
            workflowEditActionId: options.workflowEditActionId,
            sendSelectionOnChange: false,
            enablePagination: false,
            withSaveBar: false,
            
            stateful: false,
            
            columns: [],
            showColumnMenuFilteringLimit: true,
            showColumnMenuSortOption: true,
            
            messageTarget: options.messageTarget
        });
        
        var dialog = Ext.create("Ametys.window.DialogBox", {
            title: options.title || "{{i18n plugin.cms:WIDGET_SELECTCONTENT_EDITBUTTON_DIALOG_TITLE}}",
            
            closeAction : 'destroy',
            width : Math.max(550, window.innerWidth * 0.8),
            minHeight: 250,
            maxHeight : Math.max(500, window.innerHeight * 0.8),
            layout: 'fit',
            
            items: [
                grid
            ],
            
            defaultButton: 'okButton',
            referenceHolder: true,
            
            // Buttons
            buttons : [{
                    reference: 'okButton',
                    text :"{{i18n plugin.cms:WIDGET_SELECTCONTENT_EDITBUTTON_DIALOG_OK}}",
                    handler: function () {
                        this._ok(dialog, grid, multiple, callback);
                    },
                    scope: this
                }, {
                    text :'{{i18n plugin.cms:WIDGET_SELECTCONTENT_EDITBUTTON_DIALOG_CANCEL}}',
                    handler: function () {
                        dialog.close();
                    },
                    scope: this
                }
            ],
            
            listeners: {
                'close': function() {
                    if (!dialog.doNotCallCallback)
                    {
                        grid.discardChanges(false, function() {
                            if (callback)
                            {
                                callback(null);
                            }
                        });
                    }
                }
            }
        });
        dialog.show();

        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.cms.search.cocoon.ContentGridComponent",
            methodName: "getColumnsAndValues",
            parameters: [contentsIds, contentType, options.view || ""],
            callback: {
                 handler: function(data) { 
                    if (!data)
                    {
                        dialog.close();
                    }
                    else
                    {
                        this._gotColumns(grid, data, dialog)
                    }
                 },
                 scope: this,
                 ignoreOnError: false
             },
            waitMessage: true,
            errorMessage: true
        });
    },
    
    /**
     * @private
     * Callback of getColumns
     * @param {Ext.grid.Panel} grid The grid
     * @param {Object} data The columns to display
     * @param {Ametys.window.DialogBox} dialog The dialog box
     */
    _gotColumns: function(grid, data, dialog)
    {
        if (data["noright-contents"].length > 0)
        {
            let noRightPanelCfg = {
                xtype: 'component',
                itemId: 'no-right-alert',
                ui: 'tool-hintmessage',
            }
            
            if (data["noright-contents"].length == 1)
            {
                noRightPanelCfg.html = "{{i18n plugin.cms:WIDGET_SELECTCONTENT_EDITBUTTON_DIALOG_NO_RIGHT}}";
            }
            else
            {
                noRightPanelCfg.tpl = "{{i18n plugin.cms:WIDGET_SELECTCONTENT_EDITBUTTON_DIALOG_NO_RIGHTS}}";
                noRightPanelCfg.data = {count : data["noright-contents"].length};
            }
            dialog.addDocked([noRightPanelCfg]);
        }
        
        var fields = Ametys.plugins.cms.search.SearchGridHelper.getFieldsFromJson(data.columns);
        fields.push({name: 'id'});

        var columns = Ametys.plugins.cms.search.SearchGridHelper.getColumnsFromJson(data.columns, true, null);
        
        var store = Ext.create('Ext.data.Store', { 
            model: this._createModel(fields, data.contentType, data.view) 
        });
        store.loadRawData(data.contents)
        
        grid.reconfigure(store, columns);
    },
    
    /**
     * @private
     * Creates the model for the store.
     * Override this method for defining your own default fields
     * @param {Object[]} [fields] The fields for this model
     * @param {String} contentType The content type
     * @param {String} view The view name
     */
    _createModel: function(fields, contentType, view)
    {
        var modelName = "Ametys.cms.form.widget.SelectContent.EditContentsDialogBox-" + contentType + "-" + view;
        
        if (Ext.data.schema.Schema.get('default').hasEntity(modelName)) 
        {
            Ext.data.schema.Schema.get('default').getEntity(modelName).replaceFields(fields, true);
        }
        else
        {
            Ext.define(modelName, {
                extend: 'Ext.data.Model',
                schema: 'default',
                fields: fields
            });
        }
        
        return modelName;
    },
    
    /**
     * @private
     * Listener when ok is pressed
     * @param {Ametys.window.DialogBox} dialog The dialog box
     * @param {Ametys.cms.content.EditContentsGrid} grid The edition grid
     * @param {Boolean} multiple Was the initial value multiple
     * @param {Function} callback The callback to call. Can be null.
     */
    _ok: function (dialog, grid, multiple, callback)
    {
        grid._saveEdition(function (success) {
            if (success)
            {
                var newContents = [];
                grid.getStore().getData().each(function(record) {
                    newContents.push({
                        id: record.getId(),
                        title: record.get("title")
                    });
                });
                
                if (!multiple)
                {
                    if (newContents.length > 0)
                    {
                        newContents = newContents[0];
                    }
                    else
                    {
                        newContents = null;
                    }
                }
                
                dialog.doNotCallCallback = true;
                dialog.close();
                
                if (callback)
                {
                    callback(newContents);
                }
                
            }
        });
    }
});