/*
 *  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 UI helper provides a dialog to choose a query container from tree. 
 * See #open method.
 * @private
 */
Ext.define('Ametys.plugins.queriesdirectory.helper.ChooseQueryContainer', {
    singleton: true,
    
    /**
     * @property {Ametys.window.DialogBox} _box The dialog box
     * @private
     */
    /**
     * @property {Ametys.plugins.queriesdirectory.tree.QueriesTree} _tree The tree
     * @private
     */
    /**
     * @property {Function} _cbFn The callback function to call after a container has been chosen.
     * @private
     */
    
    /**
     * Allow the user to choose a query container through a tree in a dialog box
     * @param {Object} config The configuration options :
     * @param {String} [config.iconCls=ametysicon-file98] One or more CSS classes to apply to dialog's icon. Can be null to use the default one or use the icon instead.
     * @param {String} config.title The title of the dialog box.
     * @param {String} config.helpmessage The message displayed at the top of the dialog box.
     * @param {Function} config.callback The method that will be called when the dialog box is closed. The method can return false to cancel the closing action (you might display an error message in this case). Callback parameters are : 
     * @param {String} config.callback.id The id of the query container
     */
    open: function(config)
    {
        this._cbFn = config.callback || Ext.emptyFn;
        this._createDialogBox(config.iconCls, config.title, config.helpmessage);
        this._box.show();
    },
    
    /**
     * Creates the dialog box. The box is destroyed on close action
     * @param {String} iconCls One or more CSS classes to apply to dialog's icon. Can be null to use the default one or use the icon instead.
     * @param {String} title The title of the dialog box.
     * @param {String} helpmessage The message displayed at the top of the dialog box.
     * @private
     */
    _createDialogBox: function(iconCls, title, helpmessage)
    {
        this._tree = Ext.create('Ametys.plugins.queriesdirectory.tree.QueriesTree', {
            itemId: 'tree',
            rootVisible: true,
            border: true,
            height: 290,
            
            columns: [{
                xtype: 'treecolumn', 
                header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_TITLE}}", 
                flex: 1,
                dataIndex: 'text', 
                editor: {
                    xtype: 'textfield',
                    allowBlank: false,
                    selectOnFocus: true
                }
            }],
            hideHeaders: true,
            
            selModel: {
                mode: 'SINGLE',
                allowDeselect: false
            },
            onlyContainers: true,
            profile: 'write_access',
            
            listeners: {
                'selectionchange': this._onSelectionChange,
                scope: this
            }
        });
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: title,
            iconCls: iconCls || 'ametysicon-file98',
            
            width: 410,
            scrollable: false,
            
            items: [{
                    xtype: 'component',
                    cls: 'a-text',
                    html: helpmessage
                }, 
                this._tree,
                {
                    xtype: 'component',
                    cls: 'a-text',
                    html: "<a class='action'>{{i18n PLUGINS_QUERIESDIRECTORY_WIDGET_CONTAINER_DIALOG_CREATE}}</a>",
                    listeners: {
                        'afterrender': function(cmp) {
                            cmp.mon(cmp.getEl(), 'click', this._addContainer, this, {delegate: 'a.action'});
                        },
                        scope: this
                    }
                }
            ],
            
            closeAction: 'destroy',
            
            referenceHolder: true,
            defaultButton: 'validate',
            
            buttons : [{
                reference: 'validate',
                text: "{{i18n PLUGINS_QUERIESDIRECTORY_WIDGET_CONTAINER_DIALOG_OK_BTN}}",
                disabled: true,
                handler: this._ok,
                scope: this
            }, {
                text: "{{i18n PLUGINS_QUERIESDIRECTORY_WIDGET_CONTAINER_DIALOG_CANCEL_BTN}}",
                handler: Ext.bind(function() { this._box.close(); }, this)
            }]
        });
    },
    
    /**
     * @private
     * Function called when the user clicks on the link to create a new query container
     */
    _addContainer: function()
    {
        var sel = this._tree.getSelection(),
            parentId;
        if (sel.length > 0)
        {
            var parent = sel[0];
            if (parent.isQuery)
            {
                parentId = parent.parentNode.getId();
            }
            else
            {
                parentId = parent.getId();
            }
        }
        else
        {
            parentId = 'root';
        }
        
        Ametys.plugins.queriesdirectory.QueriesDAO.createQueryContainer([parentId, "{{i18n PLUGINS_QUERIESDIRECTORY_CREATE_CONTAINER_DEFAULT_NAME}}"]);
    },
    
    /**
     * @private
     * 'ok' button click handler.
     */
    _ok: function()
    {
        var record = this._tree.getSelectionModel().getSelection()[0];
        if (!record)
        {
            return;
        }
        
        var id = record.getId();
        if (this._cbFn(id) !== false)
        {
            this._box.close();
        }
    },
    
    /**
     * @private
     * Listener on selection change in the tree.
     * @param {Ext.selection.Model} sm The selection model
     * @param {Ext.data.Model[]} selected The selected records
     */
    _onSelectionChange: function(sm, selected)
    {
        var node = selected[0],
            store = this._tree.getStore(),
            rootNode = store.getRoot(),
            okBtn = this._box.getDockedItems('toolbar[dock="bottom"]')[0].items.getAt(0);
        
        okBtn.setDisabled(node == null || node == rootNode || !node.get('canWrite'));
    }
});