// Copyright 1984-2019 The MathWorks, Inc.
// All Rights Reserved.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.text.DecimalFormat;

public class RequestSpeedMeter extends JPanel {
    private double fastestTime = Double.MAX_VALUE;
    private double totalTime = 0.0;
    private double averageTime = 0.0;
    private double slowestTime = Double.MIN_NORMAL;
    private long requestCount = 0;
    private final JLabel fAverageTimeLabel;
    private final JLabel fMaxTimeLabel;
    private final JLabel fMinTimeLabel;
    private final JLabel fTotalRequestsLabel;
    private static final double precision = 100.0;

    public RequestSpeedMeter() {
        fAverageTimeLabel = new JLabel();
        fMaxTimeLabel = new JLabel();
        fMinTimeLabel = new JLabel();
        fTotalRequestsLabel = new JLabel();

        setBorder(new LineBorder(getBackground().darker()));
        setLayout(new GridBagLayout());
        
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 2;
        c.gridy = 2;
        add(new JLabel("Total requests: "), c); 
        c.gridx = 4;
        add(fTotalRequestsLabel, c); 
        c.gridx = 2;
        c.gridy = 4;
        add(new JLabel("Avg request time: "), c); 
        c.gridx = 4;
        add(fAverageTimeLabel, c); 
        c.gridx = 2;
        c.gridy = 6;
        add(new JLabel("Max request time: "), c); 
        c.gridx = 4;
        add(fMaxTimeLabel, c); 
        c.gridx = 2;
        c.gridy = 8;
        add(new JLabel("Min request time: "), c); 
        c.gridx = 4;
        add(fMinTimeLabel, c);
    }

    public void logTime(double time) {
        if ( time > slowestTime ) {
            slowestTime = time;
        }
        if ( time < fastestTime ) {
            fastestTime = time;
        }
        totalTime += time;
        ++requestCount;
        averageTime = Math.floor( totalTime * precision / requestCount ) / precision;

        DecimalFormat format = new DecimalFormat("#######.0 ");
        fAverageTimeLabel.setText(format.format(averageTime) + " ms ");
        fMaxTimeLabel.setText(format.format(slowestTime) + " ms ");
        fMinTimeLabel.setText(format.format(fastestTime) + " ms ");
        fTotalRequestsLabel.setText(Integer.toString((int)requestCount));
        revalidate();
        repaint();
    }
}
