using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using ProxyTunnel.Models;
using ProxyTunnel.Transcoder;

namespace ProxyTunnel.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProxyController : ControllerBase
    {
        private readonly ILogger<ProxyController> _logger;

        public ProxyController(ILogger<ProxyController> logger)
        {
            _logger = logger;
        }
        [HttpPost]
        [Route("performbotexchange")]
        public BotExchangeResponse SimulateExternalProviderExchange([FromBody] ExternalIntegrationBotExchangeRequest actionRequest)
        {
            BotExchangeResponse botResponse = new BotExchangeResponse();

            botResponse.nextPromptSequence = getPromptSequenceForTranscript($"Hello world!");
            botResponse.branchName = BotExchangeResponse.BotExchangeBranch.PromptAndCollectNextResponse;

            botResponse.intentInfo = new IntentInfo();

            #region Check bot session state
            if (actionRequest.botSessionState != null && !string.IsNullOrWhiteSpace(actionRequest.botSessionState.ToString()))
            {
                botResponse.botSessionState = actionRequest.botSessionState;
            }
            else
            {
                botResponse.botSessionState = new Dictionary<string, string>();
            }
            #endregion


            botResponse.nextPromptBehaviors = null; // TODO---might need some examples

            // Check if a specific automated intent has been specified
            if (actionRequest.userInputType == UserInputType.AUTOMATED_TEXT)
            {
                // Check for standard greeting request
                if (actionRequest.userInput.ToUpper() == "WELCOME")
                {
                    botResponse.intentInfo.Intent = "Welcome";
                    botResponse.intentInfo.IntentConfidence = 100;

                    botResponse.nextPromptSequence = new PromptSequence();
                    botResponse.nextPromptSequence.prompts = new List<PromptDefinition>();

                    PromptDefinition helloWorld = new PromptDefinition();
                    helloWorld.transcript = "Hello World!";

                    botResponse.nextPromptSequence.prompts.Add(helloWorld);

                    if (actionRequest.customPayload != null)
                    {
                        try
                        {
                            JObject customPayload = JObject.FromObject(actionRequest.customPayload);

                            if (customPayload.ContainsKey("name"))
                            {
                                PromptDefinition greeting = new PromptDefinition();
                                greeting.transcript = "Welcome back " + customPayload["name"].ToString();

                                botResponse.nextPromptSequence.prompts.Add(greeting);
                            }
                            else
                            {
                                PromptDefinition greeting = new PromptDefinition();
                                greeting.transcript = "With the customPayload you provided, a bot like me could leverage it to customize logic and responses, like customizing a greeting";

                                botResponse.nextPromptSequence.prompts.Add(greeting);
                            }
                        }
                        catch
                        {

                        }
                    }
                }
            }

            if (actionRequest.userInputType == UserInputType.NO_INPUT)
            {
                if (actionRequest.userInput.ToUpper() == "SILENCE")
                {
                    botResponse.branchName = BotExchangeResponse.BotExchangeBranch.UserInputTimeout;

                    botResponse.nextPromptSequence = getPromptSequenceForTranscript("Are you still there?");

                    botResponse.intentInfo.Intent = "UserInputTimeout";
                    botResponse.intentInfo.IntentConfidence = 100;
                }
            }

            if (actionRequest.userInputType == UserInputType.TEXT)
            {
                botResponse.intentInfo.Intent = "NLU_NEEDED";
                botResponse.intentInfo.IntentConfidence = 80;

                botResponse.nextPromptSequence = getPromptSequenceForTranscript($"I heard you say '{actionRequest.userInput}'.  I will get right on that!  How else can I help you?");
            }

            if (actionRequest.userInputType == UserInputType.DTMF_AS_TEXT)
            {
                botResponse.intentInfo.Intent = "DTMF";
                botResponse.intentInfo.IntentConfidence = 100;

                botResponse.nextPromptSequence = getPromptSequenceForTranscript($"I heard you provide digits through DTMF. '{actionRequest.userInput}'.  Great numbers!  How else can I help you?");
            }

            if (actionRequest.userInputType == UserInputType.BASE64_ENCODED_G711_ULAW_WAV_FILE)
            {
                botResponse.intentInfo.Intent = "RAW_AUDIO";
                botResponse.intentInfo.IntentConfidence = 100;

                botResponse.nextPromptSequence = new PromptSequence();
                botResponse.nextPromptSequence.prompts = new List<PromptDefinition>();

                PromptDefinition rawAudio = new PromptDefinition();
                rawAudio.base64EncodedG711ulawWithWavHeader = actionRequest.base64wavFile;
                botResponse.nextPromptSequence.prompts.Add(rawAudio);

                PromptDefinition followup = new PromptDefinition();
                followup.transcript = $"I got that raw audio!  A more sophisticated Bot could perform transcription, NLU or Voice Biometric Analysis.";
                botResponse.nextPromptSequence.prompts.Add(followup);

                botResponse.intentInfo.LastUserUtterance = "IMAGINE IT WAS TRANSCRIBED.  This should be populated if so.  Return null or empty if the audio was un-transcribeable, along with 'AudioInput-Un-transcribeable' branch";
            }

            //TODO--add exchange history tracking
            //this._apiManager.ExchangeHistories.AddExchangeRecord(actionRequest.executionInfo.contactId, actionRequest, botResponse);

            return botResponse;
        }

        public static PromptSequence getPromptSequenceForTranscript(string transcript)
        {
            PromptSequence result = new PromptSequence();
            PromptDefinition prompt = new PromptDefinition();
            prompt.transcript = transcript;
            result.prompts.Add(prompt);

            return result;
        }
    }
}
