package linechart;

import javafx.scene.CustomNode;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.part.NumberAxis;
import javafx.scene.chart.part.Side;
import javafx.scene.text.Font;
import javafx.scene.Node;

/**
 *
 @author Rakesh Menon
 */

public class CPUMonitor extends CustomNode, UpdateListener {

    public-init var width = 300;
    public-init var height = 200;

    var cpuLineChartSeries : LineChart.Series[] [
        LineChart.Series name: "User" },
        LineChart.Series name: "System" },
        LineChart.Series name: "Idle" }
    ];

    var cpuLineChart = LineChart {

        translateX: 10
        translateY: 10

        title: "CPU Monitor"
        showSymbols: false
        legendSide: Side.TOP

        data: cpuLineChartSeries
        
        xAxis: NumberAxis {
            lowerBound: 1
            upperBound: 10
            tickUnit: 1
            label: "Minitues"
            labelFont: Font size: 10 }
            tickLabelTickGap: 10
            tickLabelFont: Font size: }
            labelTickGap: 10
            tickMarkLength: 10
        }
        yAxis: NumberAxis {
            lowerBound: 0
            upperBound: 100
            tickUnit: 20
            label: "CPU %"
            labelFont: Font size: 10 }
            tickLabelTickGap: 10
            tickLabelFont: Font size: }
            labelTickGap: 10
            tickMarkLength: 10
            tickMarkVisible: false
        }
        height: height - 20
        width: width - 20
    }

    var cpuData = new CPUData(this);

    override function create() : Node {
        cpuLineChart;
    }

    public function start() : Void {
        cpuData.start();
    }

    var cpuIndex = 0;
    
    public override function updateCPU(user : Integer, sys : Integer, idle : Integer) {
        
        insert LineChart.Data 
            xValue: cpuIndex
            yValue: user
        into cpuLineChartSeries[0].data;

        insert LineChart.Data {
            xValue: cpuIndex
            yValue: sys
        into cpuLineChartSeries[1].data;

        insert LineChart.Data {
            xValue: cpuIndex
            yValue: idle
        into cpuLineChartSeries[2].data;

        cpuIndex += 1;
        if(cpuIndex >= cpuLineChart.xAxis.upperBound) {
            /**
             * Shift line chart
             */
            cpuLineChart.xAxis.lowerBound += 1;
            cpuLineChart.xAxis.upperBound += 1;
            // Delete initial data
            delete cpuLineChartSeries[0].data[0];
            delete cpuLineChartSeries[1].data[0];
            delete cpuLineChartSeries[2].data[0];
        }
    }
}