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

/**
 * Widget to modify values in a repeater in a grid
 */
Ext.define('Ametys.cms.form.widget.Repeater', {
    extend:'Ametys.form.AbstractField',
    
    onFocusEnter: function(e)
    {
        this.callParent(arguments);
        
        if (!this.triggerDialogBoxOpened)
        {
            var grid = this.ownerCt.ownerCmp;
            var gridConfig = grid.getInitialConfig() || {};
    
            var editingContext = grid.editingPlugin.context;
            
            var record = editingContext.record;
            var recordId = record.getId();
            var contentId = gridConfig.contentId || grid.editingPlugin._getContentId(record);
    
            var dataIndex = editingContext.column.dataIndex;
                
            this.triggerDialogBoxOpened = true;
            
            let repeaterInfos = this._getRepeaterInfo(record, grid, dataIndex, Ext.fly(e.parentEvent.target.parentNode.parentNode).hasCls("cell-disabled"));
            
            var gridId = grid.getId();
            var contentGridId = gridConfig.contentGridId || gridId;
            
            var me = this;
            window.setTimeout(function() {
                me._openDialog(repeaterInfos, gridId, recordId, contentId, dataIndex, contentGridId, Ext.bind(me._onDialogCloseCb, me, [grid, record, dataIndex], true));
            }, 1);
        }
    },
    
    /**
     * @protected
     * Open the dialog to edit
     * @param {Object} repeaterInfos the repeater values
     * @param {String} parentGridId the grid id where the widget is used
     * @param {String} recordId The currently modified record in the parent grid
     * @param {String} contentId The currently modified content id
     * @param {String} dataIndex index of the repeater data in the record
     * @param {String} contentGridId The originial grid editing the content (can be parentGridId or one of its parent)
     * @param {Function} callback Callback when the repeater dialog is closed
     */
    _openDialog: function(repeaterInfos, parentGridId, recordId, contentId, dataIndex, contentGridId, callback)
    {
        this._dialogId = Ametys.plugins.cms.search.SearchGridRepeaterDialog.showRepeaterDialog(repeaterInfos.dialogTitle, parentGridId, recordId, contentId, repeaterInfos.subcolumns, repeaterInfos.repeaterCfg, dataIndex, repeaterInfos.attributePath, contentGridId, callback).getId();
    },
    
    /**
     * @protected
     * Get the repeater info
     * @param {Object} record the current grid's record
     * @param {Ext.grid.Panel} grid the current grid
     * @param {String} dataIndex index of the repeater data in the record
     * @param {Boolean} disabled Is the repeater disabled? 
     */
    _getRepeaterInfo(record, grid, dataIndex, disabled)
    {
        let gridConfig = grid.getInitialConfig() || {};
        
        let f = record.getProxy().getModel().getField(dataIndex);
        var subcolumns = f.subcolumns;
        
        var attributePath = (gridConfig.metadataPath ? gridConfig.metadataPath + "/" : "") + dataIndex;

        let columnTitle = grid.getColumns().filter(c => c.dataIndex == dataIndex)[0].text;
        var dialogTitle = Ext.String.escape((gridConfig.dialogTitle ? gridConfig.dialogTitle + " > " : "") + columnTitle);

        var repeaterCfg = {
            'title': columnTitle,
            'min-size': f['min-size'],
            'max-size': f['max-size'],
            'initial-size': f['initial-size'],
            'add-label': f['add-label'],
            'del-label': f['del-label'],
            'header-label': f['header-label'],
            'widget-params': f['widget-params'],
            'disabled': disabled
        };
        
        return {
            subcolumns: subcolumns,
            repeaterCfg: repeaterCfg,
            attributePath: attributePath,
            dialogTitle: dialogTitle
        }
    },
    
    /**
     * @private
     * Listener on dialog closure
     * @param {Object} repeaterValues the modified repeater values
     * @param {Ext.grid.Panel} grid the current grid
     * @param {Object} record the current grid's record
     * @param {String} dataIndex index of the repeater data in the record
     */
    _onDialogCloseCb: function(repeaterValues, grid, record, dataIndex)
    {
        this.triggerDialogBoxOpened = false;
        
        if (repeaterValues)
        {
            this._saveRepeaterValues(repeaterValues, record, dataIndex);
        }
        
        if (grid.editingPlugin && grid.editingPlugin.editing)
        {
            grid.editingPlugin.completeEdit();
        }
    },
    
    /**
     * @protected
     * Save the repeater values
     * @param {Object} repeaterValues the modified repeater values
     * @param {Object} record the current grid's record
     * @param {String} dataIndex index of the repeater data in the record
     */
    _saveRepeaterValues: function(repeaterValues, record, dataIndex)
    {
        var values = Ext.clone(Ametys.plugins.cms.search.SearchGridHelper.convertRepeater(repeaterValues, record, dataIndex));
        Ametys.cms.form.widget.Repeater.superclass.setValue.call(this, values);
    },
    
    setReadOnly: function()
    {
        Ext.getCmp(this._dialogId).setReadOnly()
    }
});