Ext.define('TP_Sources', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'image_url', type: 'string'},
        {name: 'ds_name',   type: 'string'},
        {name: 'source',    type: 'number'}
    ]
});

Ext.define('TP.PanletPNP', {
    extend: 'TP.Panlet',

    title: 'PNPGraph',
    height: 240,
    width:  420,
    //maximizable: true, // does not work stateful
    initComponent: function() {
        this.callParent();
        this.xdata.url      = '';
        this.xdata.graph    = '';
        this.xdata.source   = 0;
        this.xdata.time     = '1h';
        this.lastGraph      = '';

        this.size_adjustment_x = 97;
        this.size_adjustment_y = 50;

        /* update source selector */
        this.source_store = Ext.create('Ext.data.Store', {
            model: 'TP_Sources',
            data : [ {ds_name: '0', source: 0, image_url: ''} ]
        });
        this.updateSource = function() {
            var panel  = this;
            var form   = this.down('form').getForm();
            var values = form.getValues();
            if(values.graph && values.graph != this.lastGraph && values.graph.indexOf('host=') != -1) {
                this.lastGraph = values.graph;
                var url = values.graph.replace(/\/image\?/, '/json?');
                Ext.Ajax.request({
                    url: url,
                    method: 'POST',
                    callback: function(options, success, response) {
                        var data = [];
                        var tmp  = TP.getResponse(panel, response);
                        if(tmp) {
                            for(var nr in tmp) {
                                var row = tmp[nr];
                                var match = row.image_url.match(/\&source=(\d+)\&/);
                                data[match[1]] = {
                                    ds_name: tmp[nr].ds_name,
                                    source:  match[1]
                                };
                            }
                        }
                        panel.source_combo.store.removeAll();
                        for(var nr in data) {
                            panel.source_combo.store.loadRawData(data[nr], true);
                        }
                        panel.source_combo.setValue(panel.xdata.source);
                    }
                });
            }
        };
        this.loader = {};

        /* update graph source */
        this.refreshHandler = function() {
            if(this.xdata.graph == '') {
                return;
            }
            var imgPanel = this.items.getAt(1);
            var size     = imgPanel.getSize();
            var url      = this.xdata.graph + '&view=1&source='+this.xdata.source;
            var now      = new Date();
            url = url + '&start=' + (Math.round(now.getTime()/1000) - TP.timeframe2seconds(this.xdata.time));
            url = url + '&end='   + Math.round(now.getTime()/1000);
            if(size.height > 1 && (size.height - this.size_adjustment_y) < 81) {
                url = url + '&graph_width=' + size.width;
                url = url + '&graph_height='+ size.height;
            } else {
                url = url + '&graph_width=' +(size.width  - this.size_adjustment_x);
                url = url + '&graph_height='+(size.height - this.size_adjustment_y);
            }
            if(this.loader.loadMask == true) { this.imgMask.show(); }
            imgPanel.setSrc(url);
        };

        /* panel content should be in an image */
        this.imgItem = new Ext.Img({
            src:   Ext.BLANK_IMAGE_URL,
            listeners: {
                afterrender: function (me) {
                    me.el.on({
                        load: function (evt, ele, opts) {
                            var panel = me.up('panel');
                            var refresh = panel.getTool('refresh') || panel.getTool('broken');
                            refresh.setType('refresh');
                            panel.adjustImgSize();
                            panel.imgMask.hide();
                        },
                        error: function (evt, ele, opts) {
                            var panel = me.up('panel');
                            var refresh = panel.getTool('refresh') || panel.getTool('broken');
                            refresh.setType('broken');
                            panel.imgMask.hide();
                        }
                    });
                }
            }
        });
        this.add(this.imgItem);
        this.imgMask = new Ext.LoadMask(this.imgItem, {msg:"Loading..."});

        this.graph_store = new Ext.data.Store({
                fields: ['text', 'url'],
                data: []
        });

        this.graph_combo = new Ext.form.field.ComboBox({
            fieldLabel:     'Graph',
            name:           'graph',
            queryMode:      'local',
            valueField:     'url',
            displayField:   'text',
            store:          this.graph_store,
            listeners: {
                select: function( combo, records, eOpts ) {
                    panel = combo.up('panel').up('panel').up('panel');
                    panel.xdata.source = 0;
                    panel.updateSource();
                },
                change: function( combo, newValue, oldValue, eOpts ) {
                    panel = combo.up('panel').up('panel').up('panel');
                    panel.updateSource();
                }
            }
        });
        this.down('form').add(this.graph_combo);

        this.source_combo = new Ext.form.field.ComboBox({
            fieldLabel:     'Source',
            name:           'source',
            queryMode:      'local',
            displayField:   'ds_name',
            valueField:     'source',
            forceSelection: true,
            editable:       false,
            store:          this.source_store
        });
        this.down('form').add(this.source_combo);

        this.down('form').add({
            fieldLabel:     'Time Frame',
            xtype:          'textfield',
            name:           'time'
        });

        /* auto load when url is set */
        this.addListener('afterrender', function() {
            if(this.xdata.graph == '') {
                this.gearHandler();
            } else {
                this.refreshHandler();
            }
        });
        this.addListener('resize', function(This, adjWidth, adjHeight, eOpts) {
            var size     = This.getSize();
            // not on initial resizing
            if(size.width != adjWidth || size.height != adjHeight) {
                this.size_adjustment_x += adjWidth;
                this.size_adjustment_y += adjHeight;
            }
            this.refreshHandler();
        });

        /* available graphs loader */
        this.loader = {
            autoLoad: false,
            renderer: 'data',
            scope:    this,
            url:      'panorama.cgi?task=pnp_graphs',
            ajaxOptions: { method: 'POST' },
            loading:  false,
            listeners: {
                'beforeload': function(This, options, eOpts) {
                    if(this.loading) {
                        return false;
                    }
                    this.loading = true;
                    return true;
                }
            },
            callback: function(This, success, response, options) {
                This.loading = false;
                var data  = TP.getResponse(this, response);
                if(data) {
                    this.graph_store = Ext.create('Ext.data.Store', {
                        data:  data,
                        fields: ['text', 'url'],
                        proxy: {
                            type: 'memory',
                            reader: {
                                type: 'json',
                                root: 'data'
                            }
                        }
                    });
                    this.graph_combo.store = this.graph_store;
                    this.graph_combo.setValue(this.xdata.graph);
                }
            }
        };
        this.gearInitCallback = function(This) {
            this.loader.load({});
        };

        /* adjust size of image */
        this.adjustImgSize = function() {
            var imgPanel = this.items.getAt(1);
            var size     = imgPanel.getSize();
            var naturalWidth  = imgPanel.getEl().dom.naturalWidth;
            var naturalHeight = imgPanel.getEl().dom.naturalHeight;
            if(naturalWidth && naturalWidth > 81 && size.height - this.size_adjustment_y > 81) {
                this.size_adjustment_x += (naturalWidth  - size.width);
                this.size_adjustment_y += (naturalHeight - size.height);
            }
        }
    }
});
