$(function () {
    /*
     * Flot Interactive Chart
     * -----------------------
     */
    // We use an inline data source in the example, usually data would
    // be fetched from a server
    var mem_data = [], cpu_data = [], totalPoints = 100;

    requestMemoryMaxData();

    function getZeroData(mem_data) {

        if (mem_data.length > 0)
            mem_data = mem_data.slice(1);

        // Do a random walk
        while (mem_data.length < totalPoints) {

            var prev = mem_data.length > 0 ? mem_data[mem_data.length - 1] : 50,
                y = 0;

            if (y < 0) {
                y = 0
            } else if (y > 100) {
                y = 100
            }

            mem_data.push(y)
        }

        // Zip the generated y values with the x values
        var res = [];
        for (var i = 0; i < mem_data.length; ++i) {
            res.push([i, mem_data[i]])
        }

        return res
    }

    function requestCPUData()
    {
        $.ajax({
            url: contextPath + '/server/metrics/system.cpu.usage',
            dataType: 'json',
            async: true,
            success: function (data) {
                var cpuValue = data.measurements[0].value * 100;


                interactive_plot_cpu.setData([addCPUData(cpuValue)]);


                // Since the axes don't change, we don't need to call plot.setupGrid()
                interactive_plot_cpu.draw();
                if (realtime === 'on')
                    setTimeout(update, updateInterval)
            }
        });
    }

    function requestMemoryData()
    {
        $.ajax({
            url: contextPath + '/server/metrics/jvm.memory.used',
            dataType: 'json',
            async: true,
            success: function (data) {
                var memoryValue = data.measurements[0].value;

                var result = addMemoryData(memoryValue);

                var max = result[1];

                interactive_plot.getAxes().yaxis.max = max + 100;
                interactive_plot.setData([result[0]]);


                // Since the axes don't change, we don't need to call plot.setupGrid()
                interactive_plot.draw()
            }
        });
    }


    function requestMemoryMaxData()
    {
        $.ajax({
            url: contextPath+'/server/metrics/jvm.memory.max' ,
            dataType : 'json' ,
            success: function(data) {
                var memoryValue = data.measurements[0].value/1000000;

                interactive_plot = $.plot('#interactive', [getZeroData(mem_data)], {
                    grid: {
                        borderColor: '#f3f3f3',
                        borderWidth: 1,
                        tickColor: '#f3f3f3'
                    },
                    series: {
                        shadowSize: 0, // Drawing is faster without shadows
                        color: '#3c8dbc'
                    },
                    lines: {
                        fill: true, //Converts the line chart to area chart
                        color: '#3c8dbc'
                    },
                    yaxis: {
                        min: 0,
                        max: memoryValue,
                        show: true
                    },
                    xaxis: {
                        show: true
                    }
                })
            }
        });
    }

    function addMemoryData(mValue) {
        if (mem_data.length >= totalPoints)
            mem_data = mem_data.slice(1)
        else {
            mem_data = mem_data;
        }

        mem_data.push(mValue/(1024*1024));


        var newData = [];
        var max =0 ;
        for(var i in mem_data)
        {
            newData.push([i,mem_data[i]]);

            if(mem_data[i]>max) max = mem_data[i];
        }


        return [newData,max]
    }

    function addCPUData(mValue) {
        if (cpu_data.length >= totalPoints)
            cpu_data = cpu_data.slice(1)
        else {
            cpu_data = cpu_data;
        }

        cpu_data.push(mValue);


        var newData = [];
        for(var i in cpu_data)
        {
            newData.push([i,cpu_data[i]]);
        }
        return newData
    }


    var interactive_plot = $.plot('#interactive', [getZeroData(mem_data)], {
        grid: {
            borderColor: '#f3f3f3',
            borderWidth: 1,
            tickColor: '#f3f3f3'
        },
        series: {
            shadowSize: 0, // Drawing is faster without shadows
            color: '#3c8dbc'
        },
        lines: {
            fill: true, //Converts the line chart to area chart
            color: '#3c8dbc'
        },
        yaxis: {
            min: 0,
            max: 1000,
            show: true
        },
        xaxis: {
            show: true
        }
    });

    var interactive_plot_cpu = $.plot('#interactive-cpu', [getZeroData(cpu_data)], {
        grid: {
            borderColor: '#f3f3f3',
            borderWidth: 1,
            tickColor: '#f3f3f3'
        },
        series: {
            shadowSize: 0, // Drawing is faster without shadows
            color: '#3c8dbc'
        },
        lines: {
            fill: true, //Converts the line chart to area chart
            color: '#3c8dbc'
        },
        yaxis: {
            min: 0,
            max: 100,
            show: true
        },
        xaxis: {
            show: true
        }
    });

    var updateInterval = 1000; //Fetch data ever x milliseconds
    var realtime = 'on'; //If == to on then fetch data every x seconds. else stop fetching
    function update() {

        requestCPUData();
        requestMemoryData();
    }

    //INITIALIZE REALTIME DATA FETCHING
    if (realtime === 'on') {
        update()
    }
    //REALTIME TOGGLE
    $('#realtime .btn').click(function () {
        if ($(this).data('toggle') === 'on') {
            realtime = 'on'
        } else {
            realtime = 'off'
        }
        update()
    })
    //REALTIME TOGGLE
    $('#realtime-cpu .btn').click(function () {
        if ($(this).data('toggle') === 'on') {
            realtime = 'on'
        } else {
            realtime = 'off'
        }
        update()
    })
    /*
     * END INTERACTIVE CHART
     */
});