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

/**
 * Tool showing the script text input to type into.
 * @private
 */
Ext.define('Ametys.plugins.coreui.script.ScriptHelpTool',
{
    extend: 'Ametys.tool.Tool',
    
    setParams: function(params) {
        this.callParent(arguments);
        this.showOutOfDate();
    },
    
    createPanel: function()
    {
        var me = this;
        
        var store = Ext.create('Ext.data.Store', {
            model: 'Ametys.plugins.coreui.script.ScriptHelpTool.Item',
            
            groupField: 'namespace',
            sorters: 'nameOrder',
            
            proxy: {
                type: 'ametys',
                role: 'org.ametys.plugins.core.ui.script.ScriptHandler',
                methodName: 'getScriptBindingDescription',
                methodArguments: [],
                reader: {
                    type: 'json'
                }
            }
        });
        
        this._grid = Ext.create("Ext.grid.Panel", {
            flex: 1,
            
            store: store,
            
            features: [{
                ftype: 'grouping',
                startCollapsed: false,
                groupHeaderTpl: '{name}'
            }],
            
            plugins: {
                rowexpander: {
                    rowBodyTpl: new Ext.XTemplate(
                        "<tpl if=\"examples.length &gt; 0\">"
                            + "<tpl for=\"examples\">"
                                + "<tpl if=\"text\"><p>{text}</p></tpl>"
                                + "<tpl if=\"code\"><pre class=\"example\">{code}</pre></tpl>"
                            + "</tpl>"
                        + "<tpl else>"
                            + "<p>{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_NO_EXAMPLE}}</p>"
                        + "</tpl>"
                    )
                }
            },
            
            viewConfig: {
                enableTextSelection: true
            },
            
            hideHeaders: true,
            columns: [
                { header: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_COLS_NAME}}", menuDisabled : true, sortable: true, groupable: false, flex: 1, dataIndex: 'nameOrder', renderer: function(v, m, record) { return "<span title=\"" + record.data.typeLabel + "\" class=\"type-" + record.data.type + "\">" + record.data.typeIcon + "</span>" + "<b>" + record.data.name + "</b>"; } },
                { header: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_COLS_NAMESPACE}}", hidden: true, sortable: true, groupable: true, width: 100, dataIndex: 'namespace'  },
                { header: "", width: 40, dataIndex: 'empty' } // scrollbar issue when selecting a name
            ]
        });
        
        var filter = Ext.create("Ext.Container", {
            layout: { 
                type: 'hbox',
                align: 'stretch'
            },
            items: [
                {
                    xtype: 'tbspacer',
                    flex: 0.0001
                },
                {
                    // Filter input
                    xtype: 'textfield',
                    cls: 'ametys',
                    maxWidth: 300,
                    flex: 1,
                    itemId: 'search-filter-input',
                    emptyText: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPTHELP_FILTER_PLACEHOLDER}}",
                    minLength: 0,
                    msgTarget: 'qtip',
                    listeners: {change: Ext.bind(this._filter, this)},
                    style: {
                        marginRight: '0px'
                    }
                }, {
                    // Clear filter
                    xtype: 'button',
                    tooltip: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPTHELP_FILTER_CLEAR}}",
                    handler: function() { this.ownerCt.getComponent('search-filter-input').reset(); },
                    iconCls: 'a-btn-glyph ametysicon-eraser11 size-16',
                    cls: 'a-btn-light'
                }
            ]
        });
        
        return new Ext.create("Ext.Container", {
            cls: 'uitool-script-help',
            layout: { type: 'vbox', align: 'stretch' },
            items: [
                Ext.create("Ext.Component", {
                    cls: 'intro',
                    html: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT}}"
                }),
                filter,
                this._grid,
                Ext.create("Ext.Component", {
                    cls: 'end',
                    html: "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_ADDITIONAL_SCRIPT}}"
                })
            ]
        });
    },
    
    /**
     * @private
     * Filter the grid
     * @param {Ext.form.field.Text} input The filter
     */
    _filter: function(input)
    {
        this._clearFilter();
        var value = input.getValue().toLowerCase();
        if (value)
        {
            this._grid.getStore().addFilter({ property: 'nameFilter', value: value, operator: 'like' })
        }
    },
    /**
     * @private
     * Clear the filter in the grid
     */
    _clearFilter: function()
    {
        this._grid.getStore().clearFilter();
    },
    
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_NOSELECTION;
    },
    
    getType: function()
    {
        return Ametys.tool.Tool.TYPE_REPOSITORY;  
    },
    
    refresh: function()
    {
        this.showRefreshing();
        this._grid.getStore().load({callback: Ext.bind(this.showRefreshed, this)});
    }
});

Ext.define('Ametys.plugins.coreui.script.ScriptHelpTool.Item', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'id' },
        { name: 'name' },
        { 
            name: 'nameFilter', 
            mapping: 'name', 
            convert: function(v, record) {
                return Ext.data.SortTypes.asNonAccentedUCString(v || "").toLowerCase(); 
            } 
        },
        { 
            name: 'nameOrder', 
            mapping: 'name', 
            convert: function(v, record) {
                var prefix = "";
                switch (record.data.type)
                {
                    case 'tutorial': prefix = "0"; break;
                    case 'variable': prefix = "1"; break; 
                    case 'function': prefix = "2"; break;
                    default: prefix = "3";
                }
                return prefix + record.data.nameFilter; 
            } 
        },
        { name: 'namespace', mapping: 'name', convert: function(v, record) { var i = v.indexOf('.'); return i == -1 ? "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_COLS_NAMESPACE_NONE}}" : v.substring(0, i); } },
        { name: 'description' },
        
        { name: 'signature' },
        { name: 'examples' },
        
        { name: 'type' },
        { name: 'typeIcon', mapping: 'type', convert: function(v) { 
                switch (v) { 
                    case 'variable': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_VARIABLE_SHORT}}"; 
                    case 'function': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_FUNCTION_SHORT}}";
                    case 'tutorial': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_TUTORIAL_SHORT}}";
                } } },
        { name: 'typeLabel', mapping: 'type', convert: function(v) { 
                switch (v) { 
                    case 'variable': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_VARIABLE}}"; 
                    case 'function': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_FUNCTION}}";
                    case 'tutorial': return "{{i18n PLUGINS_CORE_UI_TOOLS_SCRIPT_SCRIPT_HINT_TUTORIAL}}";
                } } },
        { name: 'empty', convert: function() { return ""; } }
    ]
});