using System;
using System.Threading.Tasks;
using System.Collections.Generic;

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI;
using Windows.UI.Popups;

using Amazon;
using Amazon.Runtime;
using Amazon.Lex;
using Amazon.Lex.Model;
using Amazon.Translate;
using Amazon.Translate.Model;
using Amazon.Polly;
using Amazon.Polly.Model;




// Pour plus d'informations sur le modèle d'élément Page vierge, consultez la page https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace ChatbotLex
{
	/// <summary>
	/// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
	/// </summary>
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();
			termino.Add("dentiste");
		}

		private static RegionEndpoint AWSreg = RegionEndpoint.EUWest1;
		private static BasicAWSCredentials AWSCred = new BasicAWSCredentials("AKIAJNJIHRALDFTPD3CA", "zIojTh7hY8d8B7qgLxqU6sulHT6gmgZ3bUU8FAAb");
		private static AmazonLexClient lexClient = new AmazonLexClient(AWSCred, AWSreg);
		private static AmazonTranslateClient translateClient = new AmazonTranslateClient(AWSCred, AWSreg);
		private static AmazonPollyClient pollyClient = new AmazonPollyClient(AWSCred, AWSreg);
		PostTextResponse lexResponse;

		Int32 l = 0;
		private string lexUserID = "demoLex";
		private string texteTraduit = "";
		List<string> termino = new List<string>();


		Color lightblue = new Color
		{
			A = 255,
			R = 173,
			G = 216,
			B = 230
		};
		Color coral = new Color
		{
			A = 255,
			R = 255,
			G = 127,
			B = 80
		};



		private async void btnMessage_Click(object sender, RoutedEventArgs e)
		{
			AjoutDeuxLignes(lightblue, txtMessage.Text, false);
			texteTraduit = await TraduireTextMessage(txtMessage.Text, "fr", "en");
			//texteTraduit = txtMessage.Text;
			GetLexPresponse(texteTraduit + " ");

			txtMessage.Text = "";
			txtMessage.Focus(FocusState.Keyboard);
		}

		private async Task<string> TraduireTextMessage(string texteATraduire, string langueSource, string langueDestination)
		{
			//Préparation de la requête et passage du code 
			//de la langue stockée dans le dictionnaire
			TranslateTextRequest translateRequest = new TranslateTextRequest
			{
				SourceLanguageCode = langueSource,
				TargetLanguageCode = langueDestination,
				Text = texteATraduire,
				TerminologyNames = termino
			};

			//Lancement de la traduction
			TranslateTextResponse textResponse =
			  await translateClient.TranslateTextAsync(translateRequest);

			return textResponse.TranslatedText;

		}

		private async void GetLexPresponse(string txtInputLex)
		{
			string repLex = "";

			try
			{
				PostTextRequest lexRequest = new PostTextRequest
				{
					BotAlias = "$LATEST",
					BotName = "RdvMedecin",
					UserId = lexUserID,
					InputText = txtInputLex
				};
				lexResponse = await lexClient.PostTextAsync(lexRequest);
			}
			catch (AmazonLexException e)
			{
				MessageDialog message = new MessageDialog(e.Message);
				await message.ShowAsync();
				return;
			}

			if (lexResponse.Message != null)
			{
				repLex = lexResponse.Message;
			}
			else if (lexResponse.DialogState == DialogState.ReadyForFulfillment)
			{
				repLex = $"Your appointment for a " +
					$"{lexResponse.Slots["AppointmentType"].ToString()} " +
					$"is confirmed on {lexResponse.Slots["Date"].ToString()} " +
					$"at {lexResponse.Slots["Time"].ToString()}";
			}
			else
			{
				repLex = lexResponse.DialogState.ToString();
			}
			//repLex = await TraduireTextMessage(repLex, "en", "fr");
			//lireMessage(repLex);
			AjoutDeuxLignes(coral, repLex, true);

		}
		private void lireMessage(string strLire)
		{
			SynthesizeSpeechRequest speechRequest = new SynthesizeSpeechRequest
			{
				OutputFormat = "mp3",
				LanguageCode = Amazon.Polly.LanguageCode.FrFR,
				VoiceId = VoiceId.Celine,
				Text = strLire,
				TextType = TextType.Text
			};

			mediaElt.Source = new Uri(SynthesizeSpeechUtil.GeneratePresignedUrl(AWSCred, AWSreg, speechRequest));
			mediaElt.AudioCategory = AudioCategory.Speech;
			mediaElt.Play();

		}

		private void TxtMessage_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
		{
			if (e.Key == Windows.System.VirtualKey.Enter)
				btnMessage_Click(sender, e);

		}

		private void AjoutDeuxLignes(Color couleur, String texte, Boolean booDeLex)
		{
			RowDefinition rd1 = new RowDefinition();
			RowDefinition rd2 = new RowDefinition();
			grdChat.RowDefinitions.Add(rd1);
			grdChat.RowDefinitions.Add(rd2);
			rd2.Height = new GridLength(10);

			Border border = new Border
			{
				Background = new SolidColorBrush(couleur)
			};
			TextBlock textBlock = new TextBlock
			{
				Text = texte,
				TextWrapping = TextWrapping.WrapWholeWords,
				Margin = new Thickness(10, 1, 10, 1)
			};

			if (booDeLex)
			{
				textBlock.HorizontalTextAlignment = TextAlignment.Right;
			}
			else
			{
				textBlock.HorizontalTextAlignment = TextAlignment.Left;
			};

			border.Child = textBlock;
			if (booDeLex)
			{
				Grid.SetColumn(border, 1);
			}
			else
			{
				Grid.SetColumn(border, 0);
			}
			Grid.SetColumnSpan(border, 2);
			Grid.SetRow(border, l);
			l += 2;

			grdChat.Children.Add(border);
			grdChat.Children.Add(new Border());
		}
	}
}

