using Amazon;
using Amazon.Rekognition;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.SQS;
using Amazon.SQS.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;

namespace RekoVideoVisage
{
     public partial class MainWindow : Window
    {
		//*******************************************************
		//Définir votre région et vos paramètres d'identification
		//*******************************************************
		private static readonly RegionEndpoint AWSreg = RegionEndpoint.EUWest1;
		private static readonly string AWSAccessKey = "";
		private static readonly string AWSSecretKey = "";

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

		private AmazonRekognitionClient rekCli;
        private StartCelebrityRecognitionResponse startRecognitionResponse;
        private GetCelebrityRecognitionResponse getRecognitionResponse;
        String strResultat = "";
        string strToken = "";
        String strJobTag = "";
        Random random;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            rekCli = new AmazonRekognitionClient(AWSCred, AWSreg);
            LancementAnalyse();
            txtResultat.Text = strResultat;
        }

        public void MessageSQS()
        {
            AmazonSQSClient client = new AmazonSQSClient(AWSCred, AWSreg);
            ReceiveMessageRequest request = new ReceiveMessageRequest
            {
                AttributeNames = new List<string>() { "ALL" },
                MaxNumberOfMessages = 5,
				//Indiquer l'URL de la queue SQS contenant la vidéo à analyser
				QueueUrl = "https://",
                VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds,
                WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds
            };

            ReceiveMessageResponse response = new ReceiveMessageResponse();
            do
            {
                Thread.Sleep(10000);
                response = client.ReceiveMessage(request);
            }
            while (response.Messages.Count == 0);

            foreach (Message mess in response.Messages)
            {
                string json = mess.Body;
                strResultat = "";
                JObject rss = JObject.Parse(json);
                JObject rssp = JObject.Parse((string)rss["Message"]);
                if ((string)rssp["JobTag"] == strJobTag & (string)rssp["Status"] == "SUCCEEDED")
                {
                    RecuperationResultat();
                    break;
                }
            }
            
            DeleteMessageRequest deleteMessage = new DeleteMessageRequest
            {
				//Indiquer l'URL de la queue SQS à supprimer
				QueueUrl = "https://",
                ReceiptHandle = response.Messages[0].ReceiptHandle
            };
            DeleteMessageResponse deleteMessageResponse = client.DeleteMessage(deleteMessage);
            
        }

        public void LancementAnalyse()
        {
            random = new Random();
            strToken = "Token" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();
            strJobTag = "Tag" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();
            NotificationChannel nc = new NotificationChannel
            {
				//Indiquer les ARN du rôle et du sujet SNS
                RoleArn = "",
                SNSTopicArn = ""
            };
            StartCelebrityRecognitionRequest startRecognitionRequest = new StartCelebrityRecognitionRequest
            {
                ClientRequestToken= strToken,
                JobTag= strJobTag,
                NotificationChannel= nc,
                Video= new Video
                    {
                        S3Object = new S3Object
                        {
							//Indiquer le compartiment et le nom de la vidéo à analyser
                            Bucket = "",
                            Name = ""
                        }
                    }
            };
            
            startRecognitionResponse = rekCli.StartCelebrityRecognition(startRecognitionRequest);
            MessageSQS();
            
        }

        private void  RecuperationResultat()
        {
            GetCelebrityRecognitionRequest getRecognitionRequest = new GetCelebrityRecognitionRequest
            {
                JobId= startRecognitionResponse.JobId,
                MaxResults=1000
            };
            int i = 0;
            strResultat = "";
            List<string> celebrites = new List<string>();
            bool trouve=false;
            do
            {
                getRecognitionResponse = rekCli.GetCelebrityRecognition(getRecognitionRequest);
                try
                {
                    
                    foreach (CelebrityRecognition cel in getRecognitionResponse.Celebrities)
                    {
                        foreach(string c in celebrites)
                        {
                            if (cel.Celebrity.Face.ToString() == c)
                            {
                                trouve = true;
                                break;
                            }
                        }
                        if (!trouve)
                        {
                            i++;
                            celebrites.Add(cel.Celebrity.Name);
                        }
                        trouve = false;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            } while (getRecognitionResponse.NextToken=="");

            foreach(string c in celebrites)
            {
                strResultat += $"{c}\n";
            }
            strResultat = $"{i} célébrité(s) détecté(s).\n" + strResultat;
        }
    }
}
