using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Providers.MediaInfo
{
    /// 
    /// Uses ffmpeg to create video images
    /// 
    public class AudioImageProvider : BaseMetadataProvider
    {
        /// 
        /// The _locks
        /// 
        private readonly ConcurrentDictionary _locks = new ConcurrentDictionary();
        /// 
        /// The _media encoder
        /// 
        private readonly IMediaEncoder _mediaEncoder;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The log manager.
        /// The configuration manager.
        /// The media encoder.
        public AudioImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder)
            : base(logManager, configurationManager)
        {
            _mediaEncoder = mediaEncoder;
        }
        /// 
        /// Gets a value indicating whether [refresh on version change].
        /// 
        /// true if [refresh on version change]; otherwise, false.
        protected override bool RefreshOnVersionChange
        {
            get
            {
                return true;
            }
        }
        /// 
        /// Gets the provider version.
        /// 
        /// The provider version.
        protected override string ProviderVersion
        {
            get
            {
                return "1";
            }
        }
        /// 
        /// Supportses the specified item.
        /// 
        /// The item.
        /// true if XXXX, false otherwise
        public override bool Supports(BaseItem item)
        {
            return item.LocationType == LocationType.FileSystem && item is Audio;
        }
        /// 
        /// Override this to return the date that should be compared to the last refresh date
        /// to determine if this provider should be re-fetched.
        /// 
        /// The item.
        /// DateTime.
        protected override DateTime CompareDate(BaseItem item)
        {
            return item.DateModified;
        }
        /// 
        /// Gets the priority.
        /// 
        /// The priority.
        public override MetadataProviderPriority Priority
        {
            get { return MetadataProviderPriority.Last; }
        }
        public override ItemUpdateType ItemUpdateType
        {
            get
            {
                return ItemUpdateType.ImageUpdate;
            }
        }
        /// 
        /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
        /// 
        /// The item.
        /// if set to true [force].
        /// The cancellation token.
        /// Task{System.Boolean}.
        public override async Task FetchAsync(BaseItem item, bool force, BaseProviderInfo providerInfo, CancellationToken cancellationToken)
        {
            item.ValidateImages();
            var audio = (Audio)item;
            if (string.IsNullOrEmpty(audio.PrimaryImagePath) && audio.HasEmbeddedImage)
            {
                try
                {
                    await CreateImagesForSong(audio, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException("Error extracting image for {0}", ex, item.Name);
                }
            }
            SetLastRefreshed(item, DateTime.UtcNow, providerInfo);
            return true;
        }
        /// 
        /// Creates the images for song.
        /// 
        /// The item.
        /// The cancellation token.
        /// Task.
        /// Can't extract an image unless the audio file has an embedded image.
        private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var path = GetAudioImagePath(item);
            if (!File.Exists(path))
            {
                var semaphore = GetLock(path);
                // Acquire a lock
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
                // Check again
                if (!File.Exists(path))
                {
                    try
                    {
                        var parentPath = Path.GetDirectoryName(path);
                        Directory.CreateDirectory(parentPath);
                        await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, null, path, cancellationToken).ConfigureAwait(false);
                    }
                    finally
                    {
                        semaphore.Release();
                    }
                }
                else
                {
                    semaphore.Release();
                }
            }
            // Image is already in the cache
            item.PrimaryImagePath = path;
        }
        /// 
        /// Gets the audio image path.
        /// 
        /// The item.
        /// System.String.
        private string GetAudioImagePath(Audio item)
        {
            var album = item.Parent as MusicAlbum;
            var filename = item.Album ?? string.Empty;
            filename += item.Artists.FirstOrDefault() ?? string.Empty;
            filename += album == null ? item.Id.ToString("N") + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks + "_primary";
            filename = filename.GetMD5() + ".jpg";
            var prefix = filename.Substring(0, 1);
            return Path.Combine(AudioImagesPath, prefix, filename);
        }
        /// 
        /// Gets the audio images data path.
        /// 
        /// The audio images data path.
        public string AudioImagesPath
        {
            get
            {
                return Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "extracted-audio-images");
            }
        }
        /// 
        /// Gets the lock.
        /// 
        /// The filename.
        /// SemaphoreSlim.
        private SemaphoreSlim GetLock(string filename)
        {
            return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
        }
    }
}