/*
 * 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.client;

import java.io.*;
import java.net.Socket;

/**
 *
 * @author callum
 * 
 * this class handles the connection to the server aand getting the 
 * questions and answers from it 
 */
public class FeedbackClient {
    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 19000;
    
    //coments in server project on these
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    private String question;
    private String[] answers;
    
    
    //constructor (look up more, not entirely sure on these) - conects to the server and gets the q and a
    public FeedbackClient() {
        try {
            // Try to get a connection to the server
            socket = new Socket(SERVER_IP, SERVER_PORT);
                
            // Set up input and output streams for communication
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);    //this should flush on itself so full messages will always be sent accross
                
            //get and save the servers message
            String message = in.readLine();
                
            //need to check for null to stop crash with startsWith 
            if (message != null && message.startsWith("QUESTION::")) {
                // Use the shared Protocol class to parse the message
                Protocol.ParsedQuestion parsed = Protocol.parseQuestionMessage(message);
                question = parsed.question;
                answers = parsed.answers;
            }
            else{
                throw new IOException("empty or wrong message from sserver");
            }
        } catch(IOException e) {
            System.err.println("Connection error: " + e.getMessage());
            throw new RuntimeException("Could not connect to server.", e);
        }   
    }
    
    //RETURN questions
    public String getQuestion() {
        return question;
    }
    
    //return answers
     public String[] getAnswers() {
        return answers;
    }
    
    
    //respond to server
      public void sendResponse(char choice) {
        if (out != null) {
            // Send the response in the correct format
            out.println("RESPONSE::" + choice);
        }

        try {
            // close the socket
            socket.close();
        } catch (IOException e) {
            System.err.println("Error closing socket: " + e.getMessage());
        }
    }
}
