package com.icx.javaproxytunnel.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.ArrayList;

import com.icx.javaproxytunnel.model.BotExchangeResponse;
import com.icx.javaproxytunnel.model.CustomPayload;
import com.icx.javaproxytunnel.model.ErrorDetails;
import com.icx.javaproxytunnel.model.ExternalIntegrationBotExchangeRequest;
import com.icx.javaproxytunnel.model.IntentInfo;
import com.icx.javaproxytunnel.model.PromptSequence;
import com.icx.javaproxytunnel.model.BotExchangeResponse.BotExchangeBranch;
import com.icx.javaproxytunnel.model.Prompt;
import com.icx.javaproxytunnel.model.enums.UserInputType;
import java.util.Random;
@RestController
@RequestMapping("/api/proxy")
public class ProxyController {

    @PostMapping
    public BotExchangeResponse botRequest(@RequestBody ExternalIntegrationBotExchangeRequest ivrRequest) throws IOException {

        Random rand = new Random();
        BotExchangeResponse botResponse = new BotExchangeResponse();
        // if(true) {
        //     // botResponse.setBranchName(BotExchangeResponse.BotExchangeBranch.Error);
        //     // botResponse.setCustomPayload(new CustomPayload());
        //     // botResponse.getCustomPayload().setAdditionalProp1("this is custom payload");

        //     // botResponse.setErrorDetails(new ErrorDetails());
        //     // botResponse.getErrorDetails().setSystemErrorMessage("error message");
        //     // return botResponse;
        //     throw new IOException("error message");  
        // }
        
        String textForTTS = "";
        botResponse.setBranchName(BotExchangeResponse.BotExchangeBranch.PromptAndCollectNextResponse);
        String result = "";
        botResponse.setIntentInfo(new IntentInfo());
        if (ivrRequest.getUserInputType() == UserInputType.AUTOMATED_TEXT)
        {
            result = ivrRequest.getUserInput();

            // Check for standard greeting request
            if (ivrRequest.getUserInput().toUpperCase().equals("WELCOME"))
            {
                botResponse.getIntentInfo().setIntent("Welcome");
                botResponse.getIntentInfo().setIntentConfidence(100);

                botResponse.setNextPromptSequence(new PromptSequence());

                botResponse.getNextPromptSequence().setPrompts(new ArrayList<Prompt>());


                Prompt prompt = new Prompt();
                prompt.setTranscript(result);

                botResponse.getNextPromptSequence().getPrompts().add(prompt);
            }
        }
        //check for no input request
        if (ivrRequest.getUserInputType() == UserInputType.NO_INPUT)
        {
            try
            {
                PromptSequence promptSequence = null;
                //User no input for voice 
                if (ivrRequest.getMediaType() == "voip")
                {
                    String audio = ivrRequest.getBase64WavFile();
                    promptSequence = getPromptSequenceForTranscript(audio);
                    botResponse.setNextPromptSequence(promptSequence);
                    botResponse.setBranchName(BotExchangeResponse.BotExchangeBranch.PromptAndCollectNextResponse);

                }
                else 
                {
                    String text = ivrRequest.getUserInput();
                    botResponse.setNextPromptSequence(getPromptSequenceForTranscript(text));
                    botResponse.setBranchName(BotExchangeResponse.BotExchangeBranch.PromptAndCollectNextResponse);
                }
                
            }
            catch (Exception e)
            {
                GetErrorResponse(botResponse, "Error: Problem while fetching bot response");
                return botResponse;
            }
        }
        //check for audio request
        if (ivrRequest.getUserInputType() == UserInputType.BASE64_ENCODED_G711_ULAW_WAV_FILE)
        {
            try
            {
                String userRequestAudio = ivrRequest.getBase64WavFile();
                //get audio response from converse bot 
                //string audioResponse = ConverseClient.AudioRelay(Channel.authenticate(),userRequestAudio); 
                String audioResponse = ivrRequest.getBase64WavFile();
                PromptSequence promptSequence = null;
                

                if (audioResponse != "")
                {
                    promptSequence = GetPromptSequenceForAudio(audioResponse, textForTTS);
                }
                else
                {
                   promptSequence = getPromptSequenceForTranscript(audioResponse);
                }
                botResponse.setNextPromptSequence(promptSequence);


            }
            catch (Exception e)
            {
                GetErrorResponse(botResponse, "Error: Problem while fetching bot response");
                return botResponse;
            }

        }
        if (ivrRequest.getUserInputType() == UserInputType.TEXT)
        {
            result = ivrRequest.getUserInput();
            botResponse.getIntentInfo().setIntent("NLU_NEEDED");
            botResponse.getIntentInfo().setIntentConfidence(80);
            botResponse.setNextPromptSequence(getPromptSequenceForTranscript(result));

     
        }
        return botResponse;
     }
    @GetMapping
    public String SendHelloMessage() {
        return "Hello";
    }


    private PromptSequence getPromptSequenceForTranscript(String transcript) {
        PromptSequence result = new PromptSequence();
        Prompt prompt = new Prompt();
        prompt.setTranscript(transcript);
        result.setPrompts(new ArrayList<Prompt>());
        result.getPrompts().add(prompt);
        return result;

    }
    private PromptSequence GetPromptSequenceForAudio(String audioByte, String transcripts) {
        PromptSequence result = new PromptSequence();
        Prompt rawAudio = new Prompt();
        rawAudio.setTranscript(transcripts);
        rawAudio.setBase64EncodedG711UlawWithWavHeader(audioByte);
        result.setPrompts(new ArrayList<Prompt>());
        result.getPrompts().add(rawAudio);
        return result;
    
    }
    private void GetErrorResponse(BotExchangeResponse botResponse, String errorMessage) {
        botResponse.setBranchName(BotExchangeResponse.BotExchangeBranch.Error);
        botResponse.setErrorDetails(new ErrorDetails());
        botResponse.getErrorDetails().setSystemErrorMessage(errorMessage);

    }
}