using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using Lib;
using Microsoft.Kinect;

namespace KinectUtils
{
    public static class GestureManager
    {
        static private BodyFrameReader bodyFrameReader;
        static private Body[] bodies;
        static event EventHandler GestureRecognized;
        static KinectManager KinectManager { get; set; }
        static List<BaseGesture> KnownGestures { get; set; }

        public static void AddGestures(IGestureFactory factory)
        {
            KnownGestures = (List<BaseGesture>)factory.CreateGestures();
        }
        public static void AddGesture(BaseGesture gesture)
        {
            if (!KnownGestures.Contains(gesture))
            {
                KnownGestures.Add(gesture);
                gesture.GestureRecognized += (sender, e) => GestureRecognized?.Invoke(sender, e);
            }
        }
        public static void RemoveGesture(BaseGesture gesture)
        {
            if (KnownGestures.Contains(gesture))
            {
                KnownGestures.Remove(gesture);
                gesture.GestureRecognized -= (sender, e) => GestureRecognized?.Invoke(sender, e);
            }
        }

        static public void StartAcquiringFrames(KinectManager kinectManager)
        {
            bodyFrameReader = kinectManager.Sensor.BodyFrameSource.OpenReader();
            bodyFrameReader.FrameArrived += Reader_BodyFrameArrived;
        }

        static private void Reader_BodyFrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            using (var bodyframe = e.FrameReference.AcquireFrame())
            {
                if (bodyframe != null)
                {
                    
                    if(bodies == null)
                    {
                        bodies = new Body[bodyframe.BodyCount];
                    }
                    bodyframe.GetAndRefreshBodyData(bodies);
                        if (bodies != null)
                        {
                            foreach (var body in bodies)
                            {
                                if (body.IsTracked)
                                {
                                    foreach (var gesture in KnownGestures)
                                    {
                                        gesture.TestGesture(body);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
