from helper.convertor import GetPromptSequenceForAudio, GetPromptSequenceForTranscript
from model.BotExchangeResponse import Prompt, PromptSequence, IntentInfo, BotExchangeResponse
from model.enum.BotExchangeBranch import BotExchangeBranch
from model.enum.UserInputType import UserInputType
from model.ExternalIntegrationBotExchangeRequest import external_integration_bot_exchange_request_from_dict
import flask


app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/relayExchangeResponse', methods=['POST'])
def relayExchangeResponse():
    textForTTS = ""
    json_data = flask.request.json
    ivrRequest = external_integration_bot_exchange_request_from_dict(json_data)
    botRespnse = BotExchangeResponse()
    botRespnse.branch_name = BotExchangeBranch.PromptAndCollectNextResponse
    
    
    if ivrRequest.user_input_type == UserInputType.AUTOMATED_TEXT:
        result = ivrRequest.user_input
        if ivrRequest.user_input.upper() == "WELCOME": 
            print ("in automated text")
            botRespnse.intent_info = IntentInfo()
            botRespnse.intent_info.intent = "Welcome"
            botRespnse.intent_info.intent_confidence = 100
            botRespnse.next_prompt_sequence = PromptSequence()
            botRespnse.next_prompt_sequence.prompts = []
            prompts = Prompt()
            prompts.transcript = result
            botRespnse.next_prompt_sequence.prompts.append(prompts)
    
    if ivrRequest.user_input_type == UserInputType.NO_INPUT:
        promptSequence = PromptSequence()
        if ivrRequest.media_type == "voip":
            audio = ivrRequest.base64_wav_file
            promptSequence = GetPromptSequenceForTranscript(audio)
            botRespnse.next_prompt_sequence = promptSequence
            botRespnse.branch_name = BotExchangeBranch.PromptAndCollectNextResponse
        else :
            text = ivrRequest.user_input
            botRespnse.next_prompt_sequence = GetPromptSequenceForTranscript(text)
            botRespnse.branch_name = BotExchangeBranch.PromptAndCollectNextResponse
            
    if ivrRequest.user_input_type == UserInputType.BASE64_ENCODED_G711_ULAW_WAV_FILE:
        userRequestAudio = ivrRequest.base64_wav_file
        promptSequence = PromptSequence()
        
        if userRequestAudio != "":
            promptSequence = GetPromptSequenceForAudio(userRequestAudio, textForTTS)
        else :
            promptSequence = GetPromptSequenceForTranscript(userRequestAudio)
        botRespnse.next_prompt_sequence = promptSequence
        
    if ivrRequest.user_input_type == UserInputType.TEXT:
        result = ivrRequest.user_input
        botRespnse.intent_info = IntentInfo()
        botRespnse.intent_info.intent = "NLU_NEEDED"
        botRespnse.intent_info.intent_confidence = 100
        botRespnse.next_prompt_sequence = GetPromptSequenceForTranscript(result)
    
    return botRespnse.to_dict()

app.run()