/*
 * 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 java.io.*;
import java.net.Socket;
/**
 *this class should handle each individual client
 * it should start with sending the client the question and answer
 * wait for and receive their response
 * then update the counter
 * @author callum
 */
public class ClientHandler implements Runnable {
    
    private final Socket socket;
    private final String question;
    private final String[] answers;
    private final FeedbackCounter counter;
    
    public ClientHandler(Socket socket, String question, String[] answers, FeedbackCounter counter) {
        this.socket = socket;
        this.question = question;
        this.answers = answers;
        this.counter = counter;
    }
    
    @Override
    public void run() {
        try(
            //set up a buferedreader to read input from client
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //set up a Printwriter to send to client
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true)
            ){
            //build the message to send to client from protocol message builder
            String msg = Protocol.buildQuestionMessage(question, answers);
            
            //send correctly formatted message to client
            out.println(msg);
            
            //wait for client to respond
            String response = in.readLine();
            
            //checks to make sure the reponse was right and parses it
            if (response != null && !response.trim().isEmpty()) {
                char selected = Protocol.parseResponseMessage(response.trim());
                
                //update counter for chart
                counter.increment(selected);
                
                // log in console for testing (maybe remove when done)
                System.out.println("Vote received: " + selected);
            }
        } catch (IOException e) {
            System.err.println("error in Client handling: " + e.getMessage());
        } finally {
            //close socket
             try {
                socket.close();
            } catch (IOException e) {
                // Log any problem that occurs while closing the connection
                System.err.println("Error closing client socket.");
            }
        }
    }
}
