using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bbiwarg.Images;
using bbiwarg.Graphics;

namespace bbiwarg.Detectors.Touch
{
    class TouchTracker
    {
        private OutputImage outputImage;
        private List<TouchEvent>[] detectedTouchEvents;
        private int framesUntilTracked;
        public List<TouchEvent> TrackedTouchEvents;

        public TouchTracker()
        {
            framesUntilTracked = 2;
            detectedTouchEvents = new List<TouchEvent>[framesUntilTracked];

            for (int i = 0; i < framesUntilTracked; i++)
            {
                detectedTouchEvents[i] = new List<TouchEvent>();
            }
        }

        public void setDetectedTouchEventsThisFrame(List<TouchEvent> touchEventsThisFrame, OutputImage outputImage)
        {
            this.outputImage = outputImage;

            for (int i = (framesUntilTracked - 1); i > 0; i--)
            {
                detectedTouchEvents[i] = detectedTouchEvents[i - 1];
            }
            detectedTouchEvents[0] = touchEventsThisFrame;


            findTrackedTouches();
        }

        private void findTrackedTouches()
        {
            TrackedTouchEvents = new List<TouchEvent>();

            foreach (TouchEvent te in detectedTouchEvents[0])
            {
                bool tracked = true;
                for (int i = 1; i < framesUntilTracked; i++)
                {
                    if (!hasSimilarTouchEventInFrame(te, i)) tracked = false;
                }
                if (tracked)
                {
                    outputImage.fillCircle(te.Position.IntX, te.Position.IntY, 5, Color.Yellow);
                    TrackedTouchEvents.Add(te);
                }
            }
        }

        private bool hasSimilarTouchEventInFrame(TouchEvent touchEvent, int frame)
        {
            foreach (TouchEvent te in detectedTouchEvents[frame])
            {
                if (touchEvent.isSimilarTo(te))
                    return true;
            }

            return false;
        }
    }
}
