using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Iisu;

namespace bbiwarg.InputProviders
{
    class InputProvider
    {
        public int ImageWidth { get; private set; }
        public int ImageHeight { get; private set; }
        public virtual int CurrentFrame { get { return frameCounter; }}

        protected int frameCounter = 0;

        protected IHandle handle;
        protected IDevice device;

        protected IDataHandle<Iisu.Data.IImageData> depthImage;
        protected IDataHandle<Iisu.Data.IImageData> confidenceImage;

        public void initialize()
        {
            createDevice();
            registerHandles(); 
        }

        protected void createDevice()
        {
            handle = Iisu.Iisu.Context.CreateHandle();
            IDeviceConfiguration conf = createDeviceConfiguration();
            device = handle.InitializeDevice(conf);
        }

        protected virtual IDeviceConfiguration createDeviceConfiguration()
        {
            return handle.CreateDeviceConfiguration();
        }

        protected virtual void registerHandles()
        {
            depthImage = device.RegisterDataHandle<Iisu.Data.IImageData>("SOURCE.CAMERA.DEPTH.Image");
            confidenceImage = device.RegisterDataHandle<Iisu.Data.IImageData>("SOURCE.CAMERA.CONFIDENCE.Image");
        }

        public void start() {
            device.Start();
            device.UpdateFrame(true);
            ImageWidth = (int)depthImage.Value.ImageInfos.Width;
            ImageHeight = (int)depthImage.Value.ImageInfos.Height;
            device.ReleaseFrame();
        }

        public void stop() {
            device.Stop(true);
        }

        public InputFrame getInputFrame()
        {
            device.UpdateFrame(true);
            frameCounter++;
            IntPtr rawDepthData = depthImage.Value.Raw;
            IntPtr rawConfidenceData = confidenceImage.Value.Raw;
            device.ReleaseFrame();

            return new InputFrame(CurrentFrame, ImageWidth, ImageHeight, rawDepthData, rawConfidenceData);
        }
    }
}
