/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package feedback.server;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;
/**
 *
 * @author callum
 */
public class LiveChartPanel extends JPanel {
    
    private DefaultCategoryDataset dataset;  
    private FeedbackCounter counter;        
    private String[] answers;  
    private NumberAxis yAxis;
    
    public LiveChartPanel(String question, String[] answers, FeedbackCounter counter) {
        this.counter = counter;
        this.answers = answers;

        // Fallback if question is blank
        if (question == null || question.trim().isEmpty()) {
            question = "Audience Feedback";
        }

        // Create and initialize the chart dataset
        dataset = new DefaultCategoryDataset();
        dataset.setValue(0, "Votes", answers[0]);
        dataset.setValue(0, "Votes", answers[1]);
        dataset.setValue(0, "Votes", answers[2]);

        // Create the chart
        JFreeChart chart = ChartFactory.createBarChart(
                question,        // Chart title
                "Options",       // X-axis label
                "Votes",         // Y-axis label
                dataset          // Data source
        );
        
        
         // Access and configure the Y-axis
        CategoryPlot plot = chart.getCategoryPlot();
        yAxis = (NumberAxis) plot.getRangeAxis();
        yAxis.setRange(0, 10);          // default range of y axis
        yAxis.setAutoRangeMinimumSize(10); 

        // Wrap the chart in a ChartPanel so it works in swing.  
        //no idea why this works look it up later
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(920, 450));

        setLayout(new BorderLayout());
        add(chartPanel, BorderLayout.CENTER);
    }

    /**
     * Updates the chart with the latest vote counts from FeedbackCounter.
     */
    public void updateChart() {
        int[] votes = counter.getCounts();
        dataset.setValue(votes[0], "Votes", answers[0]);
        dataset.setValue(votes[1], "Votes", answers[1]);
        dataset.setValue(votes[2], "Votes", answers[2]);
        
         // expand Y-axis if needed
        int maxVote = Math.max(votes[0], Math.max(votes[1], votes[2]));
        if (maxVote > yAxis.getUpperBound()) {
            yAxis.setRange(0, maxVote + 10);  
        }
    }
    
}
