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 StartPersonTrackingResponse startTrackingResponse;
        private GetPersonTrackingResponse getTrackingResponse;
        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 le flux 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;
                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 = ""
			};

            StartPersonTrackingRequest startTrackingRequest = new StartPersonTrackingRequest
            {
                ClientRequestToken = strToken,
                JobTag = strJobTag,
                NotificationChannel = nc,
                Video = new Video
                {
                    S3Object = new S3Object
                    {
						//Indiquer le compartiment S3 et le nom du fichier vidéo à analyser
						Bucket = "",
						Name = ""
					}
				}
            };
            
            startTrackingResponse = rekCli.StartPersonTracking(startTrackingRequest);
            MessageSQS();
            
        }

        private void  RecuperationResultat()
        {
            GetPersonTrackingRequest getTrackingRequest = new GetPersonTrackingRequest
            {
                JobId = startTrackingResponse.JobId,
                MaxResults = 1000,
                SortBy = PersonTrackingSortBy.TIMESTAMP
            };
            int i = 0;
            do
            {
                getTrackingResponse = rekCli.GetPersonTracking(getTrackingRequest);
                
                    foreach (PersonDetection pers in getTrackingResponse.Persons)
                    {
                    if (pers != null)
                    {
                        i++;
                        try
                        {
                            if (pers.Person.BoundingBox != null)
                            {
                                strResultat += $"{pers.Person.Index} - Personne détectée à {(float)pers.Timestamp / 1000} s. Top: {pers.Person.BoundingBox.Top}, Left: {pers.Person.BoundingBox.Left}. ";
                            }
                            else
                            {
                                strResultat += $"{pers.Person.Index} - Personne détectée à {(float)pers.Timestamp / 1000} s.";
                            }
                            
                            strResultat += "\n";
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }
                    }
                    }
                
            } while (getTrackingResponse.NextToken=="");

            strResultat += $"{i} visage(s) détecté(s).\n" ;
        }
    }
}
