/**
 * QuestionBot - Chatbot that distinguishes between questions and statements
 * This example demonstrates how to detect whether a message is a question
 * (ending with ?) or a statement and respond appropriately.
 *
 * Part III of the book "Introduction to Programming in Java"
 */

import java.util.*;

public class QuestionBot {
    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    private static final Map<String, List<String>> RESPONSES = new HashMap<>();
    private static final Random RANDOM = new Random();

    static {
        RESPONSES.put("question", Arrays.asList(
            "I don't know :(",
            "you tell me!"
        ));
        RESPONSES.put("statement", Arrays.asList(
            "tell me more!",
            "why do you think that?",
            "how do you feel about that?",
            "I find that extremely interesting",
            "can you elaborate on that?",
            "wow!",
            ":)"
        ));
    }

    /**
     * Method that responds to a user message.
     * @param message The user's message
     * @return The bot's response
     */
    public static String respond(String message) {
        // Checks whether the message ends with a question mark
        if (message.trim().endsWith("?")) {
            return getRandomResponse("question");
        } else {
            return getRandomResponse("statement");
        }
    }

    /**
     * Returns a random response of the specified type.
     * @param key The response category key
     * @return A random response
     */
    private static String getRandomResponse(String key) {
        List<String> possibleResponses = RESPONSES.get(key);
        return possibleResponses.get(RANDOM.nextInt(possibleResponses.size()));
    }

    /**
     * Method that sends a message to the bot and displays the dialogue.
     * @param message The user's message
     */
    public static void sendMessage(String message) {
        System.out.println(String.format(USER_TEMPLATE, message));
        String response = respond(message);
        System.out.println(String.format(BOT_TEMPLATE, response));
    }

    public static void main(String[] args) {
        // Messages ending with ?
        sendMessage("what's the weather like today?");
        sendMessage("what is your name?");

        // Messages not ending with ?
        sendMessage("I love programming chatbots");
        sendMessage("Java is an interesting language");
    }
}
