using IntermediatorBotSample.CommandHandling;
using Microsoft.Bot;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json.Linq;


namespace IntermediatorBotSample.Bot
{
    public class IntermediatorBot : IBot
    {
        private const string SampleUrl = "https://github.com/tompaana/intermediator-bot-sample";
        public int flag = 0;
        public async Task OnTurnAsync(ITurnContext context, CancellationToken ct)
        {
            var singleton = Singleton.GetInstance();
            var question = "";
            if((string)context.Activity.Text== null)
            {
                flag = 1;
                singleton.addToLog(context.Activity.Conversation.Id, "{" + DateTime.Now.ToLongTimeString().ToString() + "}" + " bot_message: " + "Hi");

                await context.SendActivityAsync("Hi");
            }
            
            //Command showOptionsCommand = new Command(Commands.ShowOptions);
            //await context.SendActivityAsync("text --> " + context.Activity.Text + "conv-id --> " + context.Activity.Conversation.Id);
            try
            {
                question = (string)context.Activity.Text;
                //var len = question.Trim().Length;
            }
            catch
            {
                singleton.addToLog(context.Activity.Conversation.Id, "{" + DateTime.Now.ToLongTimeString().ToString() + "}" + " bot_message: " + "Thank you for your patience as I am learning. In an effort to help you, please rephrase your question.");

                await context.SendActivityAsync("How may I help you today?");

            }

            try
            {
                var client = new RestClient("https://azr-qna-fsl-tst-vaboten.azurewebsites.net/qnamaker/knowledgebases/c462e3b6-5c2a-4ccc-8e07-628508062f2b/generateAnswer");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", "EndpointKey 5b214fe6-7dba-46fd-9968-c63a83407b0a");
                request.AddHeader("Content-Type", "application/json");

                string body = string.Format("\"question\":\"{0}\"", question);

                string body1 = "{\r\n " + body + "\r\n}";


                JObject json = JObject.Parse(body1);

                request.AddParameter("application/json", json, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);

                var body2 = JObject.Parse(response.Content);

                var answer = body2["answers"][0]["answer"];
                
                singleton.addToLog(context.Activity.Conversation.Id, "{" + DateTime.Now.ToLongTimeString().ToString() + "}" + " bot_message: " + answer.ToString().Replace("?",".").Replace("/"," "));

                await context.SendActivityAsync(answer.ToString());
            }
            catch
            {
                singleton.addToLog(context.Activity.Conversation.Id, "{" + DateTime.Now.ToLongTimeString().ToString() + "}" + " bot_message: " + "How may I help you.");

                await context.SendActivityAsync("How may I help you?");
            }



                /*HeroCard heroCard = new HeroCard()
                {
                    Title = "Hello!",
                    Subtitle = "I am Intermediator Bot",
                    Text = $"My purpose is to serve as a sample on how to implement the human hand-off. Click/tap the button below or type \"{new Command(Commands.ShowOptions).ToString()}\" to see all possible commands. To learn more visit <a href=\"{SampleUrl}\">{SampleUrl}</a>.",
                    Buttons = new List<CardAction>()
                    {
                        new CardAction()
                        {
                            Title = "Show options",
                            Value = showOptionsCommand.ToString(),
                            Type = ActionTypes.ImBack
                        }
                    }
                };*/
                
            /*singleton.Log("bot_message: " + "hero card displayed");
            singleton.addToLog(context.Activity.Conversation.Id, "{" + DateTime.Now.ToLongTimeString().ToString() + "}" + " bot_message: " + "hero card displayed");
*/
            /*Activity replyActivity = context.Activity.CreateReply();
            replyActivity.Attachments = new List<Attachment>() { heroCard.ToAttachment() };
            await context.SendActivityAsync(replyActivity);*/
        }

        

    }
}
