using MediaBrowser.Common.IO;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Logging;
using MoreLinq;
namespace MediaBrowser.Server.Implementations.ScheduledTasks
{
    /// 
    /// Class AudioImagesTask
    ///  
    public class AudioImagesTask : IScheduledTask
    {
        /// 
        /// Gets or sets the image cache.
        ///  
        /// The image cache. 
        public FileSystemRepository ImageCache { get; set; }
        /// 
        /// The _library manager
        ///  
        private readonly ILibraryManager _libraryManager;
        /// 
        /// The _media encoder
        ///  
        private readonly IMediaEncoder _mediaEncoder;
        private readonly ILogger _logger;
        /// 
        /// The _locks
        ///  
        private readonly ConcurrentDictionary _locks = new ConcurrentDictionary();
        private readonly List _newlyAddedItems = new List();
        private const int NewItemDelay = 60000;
        /// 
        /// The current new item timer
        ///  
        /// The new item timer. 
        private Timer NewItemTimer { get; set; }
        /// 
        /// Initializes a new instance of the   class.
        ///  
        ///  The library manager.
        ///  The media encoder.
        public AudioImagesTask(ILibraryManager libraryManager, IMediaEncoder mediaEncoder, ILogManager logManager)
        {
            _libraryManager = libraryManager;
            _mediaEncoder = mediaEncoder;
            _logger = logManager.GetLogger(GetType().Name);
            ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
            libraryManager.ItemAdded += libraryManager_ItemAdded;
            libraryManager.ItemUpdated += libraryManager_ItemAdded;
        }
        /// 
        /// Handles the ItemAdded event of the libraryManager control.
        ///  
        ///  The source of the event.
        ///  The   instance containing the event data.
        void libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
        {
            var audio = e.Item as Audio;
            if (audio != null)
            {
                lock (_newlyAddedItems)
                {
                    _newlyAddedItems.Add(audio);
                    if (NewItemTimer == null)
                    {
                        NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
                    }
                    else
                    {
                        NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
                    }
                }
            }
        }
        /// 
        /// News the item timer callback.
        ///  
        ///  The state.
        private async void NewItemTimerCallback(object state)
        {
            List newSongs;
            // Lock the list and release all resources
            lock (_newlyAddedItems)
            {
                newSongs = _newlyAddedItems.DistinctBy(i => i.Id).ToList();
                _newlyAddedItems.Clear();
                NewItemTimer.Dispose();
                NewItemTimer = null;
            }
            foreach (var item in newSongs
                .Where(i => i.LocationType == LocationType.FileSystem && string.IsNullOrEmpty(i.PrimaryImagePath) && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video))
                .Take(10))
            {
                try
                {
                    await CreateImagesForSong(item, CancellationToken.None).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error creating image for {0}", ex, item.Name);
                }
            }
        }
        /// 
        /// Gets the name of the task
        ///  
        /// The name. 
        public string Name
        {
            get { return "Audio image extraction"; }
        }
        /// 
        /// Gets the description.
        ///  
        /// The description. 
        public string Description
        {
            get { return "Extracts images from audio files that do not have external images."; }
        }
        /// 
        /// Gets the category.
        ///  
        /// The category. 
        public string Category
        {
            get { return "Library"; }
        }
        /// 
        /// Executes the task
        ///  
        ///  The cancellation token.
        ///  The progress.
        /// Task. 
        public async Task Execute(CancellationToken cancellationToken, IProgress progress)
        {
            var items = _libraryManager.RootFolder.RecursiveChildren
                .OfType()
                .Where(i => i.LocationType == LocationType.FileSystem && string.IsNullOrEmpty(i.PrimaryImagePath) && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video))
                .ToList();
            progress.Report(0);
            var numComplete = 0;
            foreach (var item in items)
            {
                try
                {
                    await CreateImagesForSong(item, cancellationToken).ConfigureAwait(false);
                }
                catch
                {
                    // Already logged at lower levels.
                    // Just don't let the task fail
                }
                numComplete++;
                double percent = numComplete;
                percent /= items.Count;
                progress.Report(100 * percent);
            }
            progress.Report(100);
        }
        /// 
        /// Creates the images for song.
        ///  
        ///  The item.
        ///  The cancellation token.
        /// Task. 
        private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (item.MediaStreams.All(i => i.Type != MediaStreamType.Video))
            {
                throw new InvalidOperationException("Can't extract an image unless the audio file has an embedded image.");
            }
            var album = item.Parent as MusicAlbum;
            var filename = item.Album ?? string.Empty;
            filename += album == null ? item.Id.ToString("N") + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks;
            var path = ImageCache.GetResourcePath(filename + "_primary", ".jpg");
            if (!ImageCache.ContainsFilePath(path))
            {
                var semaphore = GetLock(path);
                // Acquire a lock
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
                // Check again
                if (!ImageCache.ContainsFilePath(path))
                {
                    try
                    {
                        await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, path, cancellationToken).ConfigureAwait(false);
                    }
                    finally
                    {
                        semaphore.Release();
                    }
                    // Image is already in the cache
                    item.PrimaryImagePath = path;
                    await _libraryManager.UpdateItem(item, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    semaphore.Release();
                }
            }
        }
        /// 
        /// Gets the default triggers.
        ///  
        /// IEnumerable{BaseTaskTrigger}. 
        public IEnumerable GetDefaultTriggers()
        {
            return new ITaskTrigger[]
                {
                    new DailyTrigger { TimeOfDay = TimeSpan.FromHours(1) }
                };
        }
        /// 
        /// Gets the lock.
        ///  
        ///  The filename.
        /// System.Object. 
        private SemaphoreSlim GetLock(string filename)
        {
            return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
        }
    }
}