using Amazon;
using Amazon.Polly;
using Amazon.Polly.Model;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.TranscribeService;
using Amazon.TranscribeService.Model;
using Amazon.Translate;
using Amazon.Translate.Model;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;


namespace PollyEtTranslate
{
	
	public sealed partial class MainPage : Page
    {
		//*******************************************************
		//Définir votre région et vos paramètres d'identification
		//*******************************************************
		private static readonly RegionEndpoint regAWS = RegionEndpoint.EUWest1;
		private static readonly string AWSAccessKey = "";
		private static readonly string AWSSecretKey = "";

		private static readonly BasicAWSCredentials AWSCred = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey);

		public MainPage()
        {
            this.InitializeComponent();
        }

		private void BtnTranscrire_Click(object sender, RoutedEventArgs e)
		{
			Trans();
		}

		private async void Trans()
		{
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1);
			try
			{
				//création d'un client Transcribe et S3
				AmazonTranscribeServiceClient cltTrans = new AmazonTranscribeServiceClient(AWSCred, regAWS);
				AmazonS3Client s3Clt = new AmazonS3Client(AWSCred, regAWS);
				txtTranscrit.Text = "Transcription en cours - Merci de patienter !";

				//Définition des paramètres du job de transcription
				Media med = new Media();
				med.MediaFileUri = "https://s3-eu-west-1.amazonaws.com/exvoix/Lecture.mp3";
				StartTranscriptionJobRequest req = new StartTranscriptionJobRequest()
				{
					LanguageCode = "Fr-FR",
					MediaFormat = "Mp3",
					TranscriptionJobName = "trans",
					Media = med,
					OutputBucketName = "exvoix"
				};

				//Lancement du job de transcription
				StartTranscriptionJobResponse rep = await cltTrans.StartTranscriptionJobAsync(req);

				//Attente de la fin du job pour en afficher le résultat (le job est asynchrone)
				GetTranscriptionJobResponse transcriptionJobResponse;
				GetTranscriptionJobRequest jobRequest = new GetTranscriptionJobRequest()
				{
					TranscriptionJobName = "trans"
				};
				do
				{
					await Task.Delay(1000); // Wait 1000 ms
					transcriptionJobResponse = await cltTrans.GetTranscriptionJobAsync(jobRequest);
				}
				while (transcriptionJobResponse.TranscriptionJob.TranscriptionJobStatus != TranscriptionJobStatus.COMPLETED);

				//Lecture du résultat dans le fichier JSON en LINQ
				GetObjectRequest objectRequest = new GetObjectRequest
				{
					BucketName = "exvoix",
					Key = "trans.json"
				};
				GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);
				Stream stream = objectResponse.ResponseStream;
				StreamReader streamReader = new StreamReader(stream);

				JObject txtO = JObject.Parse(streamReader.ReadToEnd().ToString());
				txtTranscrit.Text = (string)txtO["results"]["transcripts"][0]["transcript"];
		
				//Suppression du job et du fichier
				DeleteObjectRequest deleteRequest = new DeleteObjectRequest
				{
					BucketName = "exvoix",
					Key = "trans.json"
				};
				DeleteObjectResponse deleteObject = await s3Clt.DeleteObjectAsync(deleteRequest);

				DeleteTranscriptionJobRequest deleteTranscriptionJob = new DeleteTranscriptionJobRequest
				{
					TranscriptionJobName = "trans"
				};
				DeleteTranscriptionJobResponse deleteTranscription = await cltTrans.DeleteTranscriptionJobAsync(deleteTranscriptionJob);

			}
			catch (AmazonTranscribeServiceException e)
			{
				MessageDialog message = new MessageDialog(e.Message);
				await message.ShowAsync();
			}
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);
		}

		private void BtnLire_Click(object sender, RoutedEventArgs e)
		{
			Lire(txtTranscrit.Text);
		}

		private void Lire(string strLire)
		{
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1);

			SynthesizeSpeechRequest speechRequest = new SynthesizeSpeechRequest
			{
				OutputFormat = "mp3",
				LanguageCode = Amazon.Polly.LanguageCode.FrFR,
				VoiceId = VoiceId.Mathieu,
				Text = strLire,
				TextType = TextType.Text
			};

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

			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);
		}

		private void BtnTrad_Click(object sender, RoutedEventArgs e)
		{
			txtTraduit.Text = "Traduction en cours";
			Traduire(txtTranscrit.Text);
		}

		private async void Traduire(string txtSource)
		{
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1);

			//Création du client de traduction
			AmazonTranslateClient translateClient = new AmazonTranslateClient(AWSCred, regAWS);

			//Création de la requête de traduction
			TranslateTextRequest translateRequest = new TranslateTextRequest
			{
				SourceLanguageCode = "fr",
				TargetLanguageCode = "en",
				Text = txtSource
			};

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

			//Affichage du texte traduit
			txtTraduit.Text = textResponse.TranslatedText;

			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);
		}

		private void BtnLireTrad_Click(object sender, RoutedEventArgs e)
		{
			LireTrad(txtTraduit.Text);
		}

		private void LireTrad(string strLire)
		{
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1);

			//Crétion de la requête de lecture
			SynthesizeSpeechRequest speechRequest = new SynthesizeSpeechRequest
			{
				OutputFormat = "mp3",
				LanguageCode = Amazon.Polly.LanguageCode.EnGB,
				VoiceId = VoiceId.Brian,
				Text = strLire,
				TextType = TextType.Text
			};

			//Affectation de la source et lecture du texte traduit
			mediaElt.Source = new Uri(SynthesizeSpeechUtil.GeneratePresignedUrl(AWSCred, regAWS, speechRequest));
			mediaElt.AudioCategory = AudioCategory.Speech;
			mediaElt.Play();

			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);

		}

		private void BtnTradEtLire_Click(object sender, RoutedEventArgs e)
		{
			TraduireEtLire(txtTranscrit.Text, "");
		}
		private async void TraduireEtLire(string txtSource, string txtDestination)
		{
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1);

			//Création du client de traduction
			AmazonTranslateClient translateClient = new AmazonTranslateClient(AWSCred, regAWS);

			//Création de la requête de traduction
			TranslateTextRequest translateRequest = new TranslateTextRequest
			{
				SourceLanguageCode = "auto", //auto provoque l'appel à Comprehend
				TargetLanguageCode = "en",
				Text = txtSource
			};

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

			//Création de la requête de lecture du texte traduit
			SynthesizeSpeechRequest speechRequest = new SynthesizeSpeechRequest
			{
				OutputFormat = "mp3",
				LanguageCode = Amazon.Polly.LanguageCode.EnGB,
				VoiceId = VoiceId.Amy,
				Text = textResponse.TranslatedText,
				TextType = TextType.Text
			};

			//Affectation de la source et lecture du texte traduit
			mediaElt.Source = new Uri(SynthesizeSpeechUtil.GeneratePresignedUrl(AWSCred, regAWS, speechRequest));
			mediaElt.AudioCategory = AudioCategory.Speech;
			mediaElt.Play();
			Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Arrow, 1);
		}

	}
}
