/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
 */

package feedback.server;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;


/**
 *
 * @author callum
 */
public class FeedbackServerUI extends javax.swing.JFrame {
    private FeedbackCounter feedbackCounter;
    private FeedbackServer server;
    private Thread serverThread;


    /**
     * Creates new form FeedbackServerUI
     */
    public FeedbackServerUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LBLTitle = new javax.swing.JLabel();
        PNLServerControlls = new javax.swing.JPanel();
        LBLQuestion = new javax.swing.JLabel();
        JSPQuestion = new javax.swing.JScrollPane();
        TXTAQuestion = new javax.swing.JTextArea();
        LBLAnswer1 = new javax.swing.JLabel();
        LBLAnswer2 = new javax.swing.JLabel();
        LBLAnswer3 = new javax.swing.JLabel();
        TXTFAnswer1 = new javax.swing.JTextField();
        TXTFAnswer2 = new javax.swing.JTextField();
        TXTFAnswer3 = new javax.swing.JTextField();
        BTNClose = new javax.swing.JButton();
        BTNStart = new javax.swing.JButton();
        PNLFeedbackChart = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Feedback Server Control Panel");
        setName("Feedback Server Control Panel"); // NOI18N
        setPreferredSize(new java.awt.Dimension(1280, 720));

        LBLTitle.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 18)); // NOI18N
        LBLTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        LBLTitle.setText("Feedback Server Control Panel");

        PNLServerControlls.setBorder(javax.swing.BorderFactory.createTitledBorder("Server controls"));
        PNLServerControlls.setToolTipText("");
        PNLServerControlls.setName("clientStuff"); // NOI18N
        PNLServerControlls.setPreferredSize(new java.awt.Dimension(312, 450));

        LBLQuestion.setText("question");

        TXTAQuestion.setColumns(20);
        TXTAQuestion.setLineWrap(true);
        TXTAQuestion.setRows(5);
        TXTAQuestion.setName(""); // NOI18N
        JSPQuestion.setViewportView(TXTAQuestion);

        LBLAnswer1.setText("answer 1");

        LBLAnswer2.setText("answer 2");

        LBLAnswer3.setText("answer 3");

        TXTFAnswer1.setToolTipText("");

        BTNClose.setText("Close");
        BTNClose.setMaximumSize(new java.awt.Dimension(75, 25));
        BTNClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BTNCloseActionPerformed(evt);
            }
        });

        BTNStart.setText("Start Server");
        BTNStart.setMaximumSize(new java.awt.Dimension(75, 25));
        BTNStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BTNStartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PNLServerControllsLayout = new javax.swing.GroupLayout(PNLServerControlls);
        PNLServerControlls.setLayout(PNLServerControllsLayout);
        PNLServerControllsLayout.setHorizontalGroup(
            PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PNLServerControllsLayout.createSequentialGroup()
                .addGroup(PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(BTNClose, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(BTNStart, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 177, Short.MAX_VALUE))
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(LBLAnswer2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(LBLAnswer1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(LBLAnswer3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(256, 256, 256))
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(TXTFAnswer1))
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(TXTFAnswer2))
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(TXTFAnswer3))
                    .addGroup(PNLServerControllsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(PNLServerControllsLayout.createSequentialGroup()
                                .addComponent(LBLQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(JSPQuestion))))
                .addContainerGap())
        );
        PNLServerControllsLayout.setVerticalGroup(
            PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PNLServerControllsLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(LBLQuestion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JSPQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(LBLAnswer1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TXTFAnswer1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(LBLAnswer2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TXTFAnswer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(LBLAnswer3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TXTFAnswer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PNLServerControllsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BTNClose, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BTNStart, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26))
        );

        LBLAnswer1.getAccessibleContext().setAccessibleName("Answer1");
        LBLAnswer2.getAccessibleContext().setAccessibleName("answer2");
        LBLAnswer3.getAccessibleContext().setAccessibleName("answer3");
        TXTFAnswer1.getAccessibleContext().setAccessibleName("");

        PNLFeedbackChart.setBorder(javax.swing.BorderFactory.createTitledBorder("Feedback Chart"));
        PNLFeedbackChart.setName("ChartPanel"); // NOI18N
        PNLFeedbackChart.setPreferredSize(new java.awt.Dimension(920, 450));

        javax.swing.GroupLayout PNLFeedbackChartLayout = new javax.swing.GroupLayout(PNLFeedbackChart);
        PNLFeedbackChart.setLayout(PNLFeedbackChartLayout);
        PNLFeedbackChartLayout.setHorizontalGroup(
            PNLFeedbackChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 736, Short.MAX_VALUE)
        );
        PNLFeedbackChartLayout.setVerticalGroup(
            PNLFeedbackChartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 442, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(LBLTitle, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PNLServerControlls, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(PNLFeedbackChart, javax.swing.GroupLayout.PREFERRED_SIZE, 746, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(LBLTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(PNLFeedbackChart, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                    .addComponent(PNLServerControlls, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BTNStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTNStartActionPerformed
    System.out.println("Start button pressed");
    // Get trimmed values from text inputs
    String question = TXTAQuestion.getText().trim();
    String answer1 = TXTFAnswer1.getText().trim();
    String answer2 = TXTFAnswer2.getText().trim();
    String answer3 = TXTFAnswer3.getText().trim();
    
     String[] answers;

    // Determine if any or all fields are filled
    boolean allEmpty = question.isEmpty() && answer1.isEmpty() && answer2.isEmpty() && answer3.isEmpty();
    boolean someEmpty = (!question.isEmpty() || !answer1.isEmpty() || !answer2.isEmpty() || !answer3.isEmpty())
                     && (question.isEmpty() || answer1.isEmpty() || answer2.isEmpty() || answer3.isEmpty());
        
    
    if (someEmpty) {
        // Show error if partial input is provided
        JOptionPane.showMessageDialog(this,
            "If any field is filled, all fields must be filled.",
            "Input Error",
            JOptionPane.ERROR_MESSAGE);
        return; 
    }
    if (allEmpty) {
        // default values
        question = "How are you feeling?";
        answers = new String[]{"happy", "okay", "unhappy"};
    } else {
        // Use entered values
        answers = new String[]{answer1, answer2, answer3};
    }
    
    // Initialize the vote counter (this should fix the issue in the feedback server class)
    feedbackCounter = new FeedbackCounter();

    // Create and embed the chart
    LiveChartPanel chart = new LiveChartPanel(question, answers, feedbackCounter);
    
     PNLFeedbackChart.removeAll();                    
    PNLFeedbackChart.setLayout(new BorderLayout());
    PNLFeedbackChart.add(chart, BorderLayout.CENTER);
    PNLFeedbackChart.revalidate();
    PNLFeedbackChart.repaint();

    // Set up chart auto-refresh
    new javax.swing.Timer(1000, e -> chart.updateChart()).start();

    // Disable inputs after starting
    TXTAQuestion.setEnabled(false);
    TXTFAnswer1.setEnabled(false);
    TXTFAnswer2.setEnabled(false);
    TXTFAnswer3.setEnabled(false);
    BTNStart.setEnabled(false);

    //starts the actual server logic in a thread so it doesnt mess with the ui
    server = new FeedbackServer(question, answers, feedbackCounter);
    serverThread = new Thread(server);
    serverThread.start();

    System.out.println("Server thread launched");
    
    }//GEN-LAST:event_BTNStartActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {
    // stop the server on close if it's running
        if (server != null) {
            server.stop();  // Closes ServerSocket
        }
        try {
        if (serverThread != null && serverThread.isAlive()) {
            serverThread.join(500);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
        System.exit(0);
    }
    
    private void BTNCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTNCloseActionPerformed
        if (server != null) {
            server.stop();  // Close ServerSocket
        }
            try {
        if (serverThread != null && serverThread.isAlive()) {
            serverThread.join(500);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
        System.exit(0);
    }//GEN-LAST:event_BTNCloseActionPerformed
        
    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BTNClose;
    private javax.swing.JButton BTNStart;
    public javax.swing.JScrollPane JSPQuestion;
    private javax.swing.JLabel LBLAnswer1;
    private javax.swing.JLabel LBLAnswer2;
    private javax.swing.JLabel LBLAnswer3;
    private javax.swing.JLabel LBLQuestion;
    private javax.swing.JLabel LBLTitle;
    private javax.swing.JPanel PNLFeedbackChart;
    private javax.swing.JPanel PNLServerControlls;
    public javax.swing.JTextArea TXTAQuestion;
    public javax.swing.JTextField TXTFAnswer1;
    public javax.swing.JTextField TXTFAnswer2;
    public javax.swing.JTextField TXTFAnswer3;
    // End of variables declaration//GEN-END:variables
}
