/*
 *  Copyright 2017 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.
 */
 
/**
 * @private
 * A sprite legend that display a description
 */
Ext.define("Ametys.plugins.admin.jvmstatus.MonitoringTool.SpriteLegend", {
    alias: 'legend.monitoring-sprite',
    extend: "Ext.chart.legend.SpriteLegend",
    
    /** @cfg {String} description A description to display over the legend */
    /**
     * @private
     * @property {Ext.chart.legend.sprite.Item} _descriptionSprite The sprite for the description
     */
    
    updateSprites: function()
    {
        this.callParent(arguments);
        
        if (!this._descriptionSprite)
        {
            // This is diry, please do not try to know who did this
            function _cut(t)
            {
                if (t)
                {
                    var count = 0;
                    var nbLines = 1;
                    var index = -1;
                    
                    while (true)
                    {
                        index = t.indexOf(" ", index + 1);
                        var otherIndex = t.indexOf("\n", index + 1);
                        if (otherIndex != -1 && otherIndex < index)
                        {
                            count = 0;
                        }
                        
                        count++;
                        if (index == -1)
                        {
                            return {text: t, y: 20 + 10*(nbLines-1)};
                        }
                        else if (count == 4)
                        {
                            count = 0;
                            nbLines++;
                            t = t.substring(0, index) + "\n" + t.substring(index + 1);
                        }
                    }
                }
                else
                {
                    return {text: "", y: 20};
                }
            }
            
            this._descriptionSprite = this.getSurface().add(
                Ext.apply(
                    {
                        type: 'text',
                        x: 5,
                        zIndex: 50
                    }, 
                    _cut(this.getInitialConfig()['description'])
                )
            );
            this.getSurface().add(this._descriptionSprite);
        }
    }
});