/*
 * 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;

/**
 *
 * @author callum
 */


/**
 * Defines the methods for building and parsing messages
 * between the server and client.
 *
 * Format:
 * message to client:  QUESTION::<question>::<A>::<B>::<C>
 * message from client: RESPONSE::<A|B|C>
 */
public class Protocol {
    
    private static final String DELIMITER = "::";
    private static final String TYPE_QUESTION = "QUESTION";
    private static final String TYPE_RESPONSE = "RESPONSE";
    
     /**
     * Builds a message to send to the client
     */
    public static String buildQuestionMessage(String question, String[] answers) {
        if (answers.length != 3) {
            throw new IllegalArgumentException("Exactly 3 answers required.");
        }

        return TYPE_QUESTION + DELIMITER +
               question + DELIMITER +
               answers[0] + DELIMITER +
               answers[1] + DELIMITER +
               answers[2];
    }
    
    
    //parses response message from client giving their vote/choice
    public static char parseResponseMessage(String message) {
        if (message == null || !message.startsWith(TYPE_RESPONSE + DELIMITER)) {
            throw new IllegalArgumentException("Invalid response format");
        }

        String[] parts = message.split(DELIMITER);
        if (parts.length != 2) {
            throw new IllegalArgumentException("Incorrect response format");
        }

        char response = parts[1].trim().toUpperCase().charAt(0);
        if (response < 'A' || response > 'C') {
            throw new IllegalArgumentException("Response must be A, B, or C");
        }

        return response;
    }
    
    
    public static class ParsedQuestion {
        public final String question;
        public final String[] answers;

        public ParsedQuestion(String question, String[] answers) {
            this.question = question;
            this.answers = answers;
        }
    }
    
    /**
     * reads/pars a message received by the client.
     */
    public static ParsedQuestion parseQuestionMessage(String message) {
        if (message == null || !message.startsWith(TYPE_QUESTION + DELIMITER)) {
            throw new IllegalArgumentException("Invalid question format");
        }

        String[] parts = message.split(DELIMITER);
        if (parts.length != 5) {
            throw new IllegalArgumentException("Expected format: QUESTION::Q::A::B::C");
        }

        return new ParsedQuestion(parts[1], new String[]{parts[2], parts[3], parts[4]});
    }

    
    
}
