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

namespace bbiwarg.InputProviders
{
    class VideoInputProvider : InputProvider
    {
        public override int CurrentFrame { get { return currentMovieFrame.Value; } }
        public String MoviePath { get; private set; }
        public bool IsPaused { get { return (playStep.Value == 0); } }

        private IParameterHandle<int> currentMovieFrame;
        private IParameterHandle<int> playStep;

        public VideoInputProvider(String moviePath)
        {
            MoviePath = moviePath;
        }

        protected override IDeviceConfiguration createDeviceConfiguration()
        {
            IDeviceConfiguration conf = base.createDeviceConfiguration();
            conf.MoviePath = MoviePath;
            return conf;
        }

        protected override void registerHandles()
        {
            base.registerHandles();

            device.RegisterParameterHandle<int>("SOURCE.MOVIE.PlayMode").Value = 1; // 0=once, 1=loop, 2=pingPong
            currentMovieFrame = device.RegisterParameterHandle<int>("SOURCE.MOVIE.CurrentFrame");
            playStep = device.RegisterParameterHandle<int>("SOURCE.MOVIE.PlayStep");
        }

        public void pause()
        {
            playStep.Value = 0;
            Logger.log("Video pause", LogSubject.VideoControls);
        }

        public void play()
        {
            playStep.Value = 1;
            Logger.log("Video play", LogSubject.VideoControls);
        }

        public void nextFrame()
        {
            playStep.Value = 1;
            int nextFrame = currentMovieFrame.Value + 1;
            while (currentMovieFrame.Value != nextFrame)
            {
                device.UpdateFrame(false);
                device.ReleaseFrame();
            }
            playStep.Value = 0;
            Logger.log("Video nextFrame", LogSubject.VideoControls);
        }

        public void previousFrame()
        {
            playStep.Value = -1;
            int previousFrame = currentMovieFrame.Value - 1;
            while (currentMovieFrame.Value != previousFrame)
            {
                device.UpdateFrame(false);
                device.ReleaseFrame();
            }
            playStep.Value = 0;
            Logger.log("Video previousFrame", LogSubject.VideoControls);
        }
    }
}
