using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Api
{
    /// 
    /// Class ServerEntryPoint
    /// 
    public class ApiEntryPoint : IServerEntryPoint
    {
        /// 
        /// The instance
        /// 
        public static ApiEntryPoint Instance;
        /// 
        /// Gets or sets the logger.
        /// 
        /// The logger.
        private ILogger Logger { get; set; }
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The logger.
        public ApiEntryPoint(ILogger logger)
        {
            Logger = logger;
            Instance = this;
        }
        /// 
        /// Runs this instance.
        /// 
        public void Run()
        {
        }
        /// 
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// 
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// 
        /// Releases unmanaged and - optionally - managed resources.
        /// 
        /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
        protected virtual void Dispose(bool dispose)
        {
            var jobCount = _activeTranscodingJobs.Count;
            Parallel.ForEach(_activeTranscodingJobs, KillTranscodingJob);
            // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
            if (jobCount > 0)
            {
                Thread.Sleep(1000);
            }
        }
        /// 
        /// The active transcoding jobs
        /// 
        private readonly List _activeTranscodingJobs = new List();
        /// 
        /// Called when [transcode beginning].
        /// 
        /// The path.
        /// The type.
        /// The process.
        /// if set to true [is video].
        /// The start time ticks.
        /// The source path.
        /// The device id.
        public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, bool isVideo, long? startTimeTicks, string sourcePath, string deviceId)
        {
            lock (_activeTranscodingJobs)
            {
                _activeTranscodingJobs.Add(new TranscodingJob
                {
                    Type = type,
                    Path = path,
                    Process = process,
                    ActiveRequestCount = 1,
                    IsVideo = isVideo,
                    StartTimeTicks = startTimeTicks,
                    SourcePath = sourcePath,
                    DeviceId = deviceId
                });
            }
        }
        /// 
        /// 
        /// The progressive
        /// 
        /// Called when [transcode failed to start].
        /// 
        /// The path.
        /// The type.
        public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
        {
            lock (_activeTranscodingJobs)
            {
                var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
                _activeTranscodingJobs.Remove(job);
            }
        }
        /// 
        /// Determines whether [has active transcoding job] [the specified path].
        /// 
        /// The path.
        /// The type.
        /// true if [has active transcoding job] [the specified path]; otherwise, false.
        public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
        {
            lock (_activeTranscodingJobs)
            {
                return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
            }
        }
        /// 
        /// Called when [transcode begin request].
        /// 
        /// The path.
        /// The type.
        public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
        {
            lock (_activeTranscodingJobs)
            {
                var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
                if (job == null)
                {
                    return;
                }
                job.ActiveRequestCount++;
                if (job.KillTimer != null)
                {
                    job.KillTimer.Dispose();
                    job.KillTimer = null;
                }
            }
        }
        /// 
        /// Called when [transcode end request].
        /// 
        /// The path.
        /// The type.
        public void OnTranscodeEndRequest(string path, TranscodingJobType type)
        {
            lock (_activeTranscodingJobs)
            {
                var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
                if (job == null)
                {
                    return;
                }
                job.ActiveRequestCount--;
                if (job.ActiveRequestCount == 0)
                {
                    // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
                    var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 1800000;
                    if (job.KillTimer == null)
                    {
                        job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
                    }
                    else
                    {
                        job.KillTimer.Change(timerDuration, Timeout.Infinite);
                    }
                }
            }
        }
        /// 
        /// Called when [transcode kill timer stopped].
        /// 
        /// The state.
        private void OnTranscodeKillTimerStopped(object state)
        {
            var job = (TranscodingJob)state;
            KillTranscodingJob(job);
        }
        /// 
        /// Kills the single transcoding job.
        /// 
        /// The device id.
        /// if set to true [is video].
        /// sourcePath
        internal void KillTranscodingJobs(string deviceId, bool isVideo)
        {
            if (string.IsNullOrEmpty(deviceId))
            {
                throw new ArgumentNullException("deviceId");
            }
            var jobs = new List();
            lock (_activeTranscodingJobs)
            {
                // This is really only needed for HLS. 
                // Progressive streams can stop on their own reliably
                jobs.AddRange(_activeTranscodingJobs.Where(i => isVideo == i.IsVideo && string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
            }
            foreach (var job in jobs)
            {
                KillTranscodingJob(job);
            }
        }
        /// 
        /// Kills the transcoding job.
        /// 
        /// The job.
        private async void KillTranscodingJob(TranscodingJob job)
        {
            lock (_activeTranscodingJobs)
            {
                _activeTranscodingJobs.Remove(job);
                if (job.KillTimer != null)
                {
                    job.KillTimer.Dispose();
                    job.KillTimer = null;
                }
            }
            var process = job.Process;
            var hasExited = true;
            try
            {
                hasExited = process.HasExited;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
            }
            if (!hasExited)
            {
                try
                {
                    Logger.Info("Killing ffmpeg process for {0}", job.Path);
                    process.Kill();
                    // Need to wait because killing is asynchronous
                    process.WaitForExit(5000);
                }
                catch (Win32Exception ex)
                {
                    Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
                }
                catch (InvalidOperationException ex)
                {
                    Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
                }
                catch (NotSupportedException ex)
                {
                    Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
                }
            }
            // Determine if it exited successfully
            var hasExitedSuccessfully = false;
            try
            {
                hasExitedSuccessfully = process.ExitCode == 0;
            }
            catch (InvalidOperationException)
            {
            }
            catch (NotSupportedException)
            {
            }
            // Dispose the process
            process.Dispose();
            // If it didn't complete successfully cleanup the partial files
            // Also don't cache output from resume points
            // Also don't cache video
            if (!hasExitedSuccessfully || job.StartTimeTicks.HasValue || job.IsVideo)
            {
                Logger.Info("Deleting partial stream file(s) {0}", job.Path);
                await Task.Delay(1000).ConfigureAwait(false);
                try
                {
                    if (job.Type == TranscodingJobType.Progressive)
                    {
                        DeleteProgressivePartialStreamFiles(job.Path);
                    }
                    else
                    {
                        DeleteHlsPartialStreamFiles(job.Path);
                    }
                }
                catch (IOException ex)
                {
                    Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, job.Path);
                }
            }
        }
        /// 
        /// Deletes the progressive partial stream files.
        /// 
        /// The output file path.
        private void DeleteProgressivePartialStreamFiles(string outputFilePath)
        {
            File.Delete(outputFilePath);
        }
        /// 
        /// Deletes the HLS partial stream files.
        /// 
        /// The output file path.
        private void DeleteHlsPartialStreamFiles(string outputFilePath)
        {
            var directory = Path.GetDirectoryName(outputFilePath);
            var name = Path.GetFileNameWithoutExtension(outputFilePath);
            var filesToDelete = Directory.EnumerateFiles(directory)
                .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
                .ToList();
            foreach (var file in filesToDelete)
            {
                try
                {
                    Logger.Info("Deleting HLS file {0}", file);
                    File.Delete(file);
                }
                catch (IOException ex)
                {
                    Logger.ErrorException("Error deleting HLS file {0}", ex, file);
                }
            }
        }
    }
    /// 
    /// Class TranscodingJob
    /// 
    public class TranscodingJob
    {
        /// 
        /// Gets or sets the path.
        /// 
        /// The path.
        public string Path { get; set; }
        /// 
        /// Gets or sets the type.
        /// 
        /// The type.
        public TranscodingJobType Type { get; set; }
        /// 
        /// Gets or sets the process.
        /// 
        /// The process.
        public Process Process { get; set; }
        /// 
        /// Gets or sets the active request count.
        /// 
        /// The active request count.
        public int ActiveRequestCount { get; set; }
        /// 
        /// Gets or sets the kill timer.
        /// 
        /// The kill timer.
        public Timer KillTimer { get; set; }
        public bool IsVideo { get; set; }
        public long? StartTimeTicks { get; set; }
        public string SourcePath { get; set; }
        public string DeviceId { get; set; }
    }
    /// 
    /// Enum TranscodingJobType
    /// 
    public enum TranscodingJobType
    {
        /// 
        /// The progressive
        /// 
        Progressive,
        /// 
        /// The HLS
        /// 
        Hls
    }
}