package org.studiorailgun.ai.conversation.evaluators;

import org.studiorailgun.Globals;
import org.studiorailgun.ai.conversation.evaluators.goal.GoalEval;
import org.studiorailgun.ai.conversation.evaluators.greet.GreetingEval;
import org.studiorailgun.ai.conversation.evaluators.query.QueryEval;
import org.studiorailgun.ai.conversation.evaluators.synthesis.ResponseEval;
import org.studiorailgun.ai.conversation.evaluators.transfer.TransferEval;
import org.studiorailgun.ai.conversation.parser.NLPParser;
import org.studiorailgun.ai.conversation.tracking.Conversation;
import org.studiorailgun.ai.conversation.tracking.Quote;
import org.studiorailgun.ai.conversation.tracking.Sentence;
import org.studiorailgun.ai.conversation.web.ConversationQuery;

/**
 * Evaluates a sentence based on data about the sentence
 */
public class EvaluationTree {

    /**
     * Number of times to evaluate response logic
     */
    static final int RESPONSE_EVAL_COUNT = 2;
    
    /**
     * Evaluates a quote
     * @param quote The quote
     */
    public static Quote evaluate(Conversation conversation, Quote quote){

        //perform NLP evaluation of the quote
        NLPParser.parse(quote);

        //add the evaluated quote to the conversation
        conversation.addQuote(ConversationQuery.getOtherParticipant(), quote);

        //evaluate each sentence
        for(Sentence sentence : quote.getSentences()){
            switch(sentence.getFunction()){
                case UTILITY: {
                    GreetingEval.evaluate(conversation, quote, sentence);
                } break;
                case QUERY: {
                    QueryEval.evaluate(conversation, quote, sentence);
                } break;
                case TRANSFER : {
                    TransferEval.evaluate(conversation, quote, sentence);
                } break;
                default: {
                    throw new UnsupportedOperationException("Unsupported quote function: " + sentence.getFunction());
                }
            }
        }


        //the response quote
        Quote response = new Quote("");


        //repeatedly check if we can generate a new sentence
        for(int i = 0; i < RESPONSE_EVAL_COUNT; i++){
            //evaluate the AI's current goal in the conversation
            GoalEval.evaluate(conversation);

            //finished evaluation (couldn't find any more goals to pursue)
            if(Globals.conversation.getGoalData().getGoal() == null){
                break;
            }

            //synthesize language based on the results of the actions performed
            Sentence newSent = ResponseEval.evaluate(conversation);
            if(newSent != null){
                response.appendSentence(newSent);
            }
        }

        //add the synthesized quote to the conversation
        conversation.addQuote(Globals.web.getAnchors().getSelfNode(), response);

        return response;
    }

}
