using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
using System.IO;
using AtariRobot;
using System.Drawing;
using MathPirate.AlternativeInputDevices.FacialRecognition;

namespace FaceExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            CvWindow rawVideo = new CvWindow("RawVideo");
            CvWindow detectedFacesVideo = new CvWindow("DetectedFaces");
            CvFont font = new CvFont(FontFace.HersheyComplexSmall, .5, .5);

            Options options = Options.GetOptions();

            CvCapture capture = null;

            if (string.IsNullOrEmpty(options.Filename))
            {
                capture = Cv.CreateCameraCapture(options.CameraIndex);
            }
            else
            {
                capture = CvCapture.FromFile(options.Filename);
            }

            int faceCount = 0;
            string extractionDir = "ExtractedFaces" + DateTime.Now.ToString("MMddyyyyHHmmss");
            
            if (!Directory.Exists(extractionDir))
            {
                Directory.CreateDirectory(extractionDir);
            }

            //double fps = capture.Fps;
            //if (fps == 0)
            //{
            //    fps = 60;
            //}
            //int frameTime = (int)(1000 / fps);

            int frameTime = 1000;


            while (Cv.WaitKey(frameTime) < 0)
            {
                IplImage frame = capture.QueryFrame();
                if (frame == null)
                {
                    break;
                }

                rawVideo.Image = frame;

                Rectangle[] faces = DetectFaces.Detect(frame);

                Bitmap frameBitmap = frame.ToBitmap();
                Bitmap[] faceBitmaps = DetectFaces.ExtractFaces(faces, frameBitmap);
                frameBitmap.Dispose();

                IplImage faceDetectImage = new IplImage(frame.Width, frame.Height, frame.Depth, frame.ElemChannels);
                frame.Copy(faceDetectImage);

                for(int faceIndex = 0; faceIndex < faces.Length; faceIndex++)
                {
                    FaceID faceID = new FaceID();
                    faceID.Location = faces[faceIndex];
                    faceID.Image = faceBitmaps[faceIndex];

                    string faceFilename = string.Format(@"{0}\Face{1:D5}.jpg", extractionDir, faceCount);
                    faceID.Image.Save(faceFilename);
                    faceCount++;

                    faceDetectImage.DrawRect(faceID.Location.Left, faceID.Location.Top, faceID.Location.Right, faceID.Location.Bottom, faceID.Identity == "WesleyCrusher" ? CvColor.Red : CvColor.Green, 2);
                }

                detectedFacesVideo.Image = faceDetectImage;
                faceDetectImage.Dispose();
            }
        }
    }
}