using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace MediaBrowser.Server.Implementations.Library
{
    /// 
    /// Class ResolverHelper
    /// 
    public static class ResolverHelper
    {
        /// 
        /// Sets the initial item values.
        /// 
        /// The item.
        /// The parent.
        /// The file system.
        /// The library manager.
        /// The directory service.
        /// Item must have a path
        public static void SetInitialItemValues(BaseItem item, Folder parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService)
        {
            // This version of the below method has no ItemResolveArgs, so we have to require the path already being set
            if (string.IsNullOrWhiteSpace(item.Path))
            {
                throw new ArgumentException("Item must have a Path");
            }
            // If the resolver didn't specify this
            if (parent != null)
            {
                item.SetParent(parent);
            }
            item.Id = libraryManager.GetNewItemId(item.Path, item.GetType());
            item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 ||
                item.Parents.Any(i => i.IsLocked);
            // Make sure DateCreated and DateModified have values
            var fileInfo = directoryService.GetFile(item.Path);
            item.DateModified = fileSystem.GetLastWriteTimeUtc(fileInfo);
            SetDateCreated(item, fileSystem, fileInfo);
            EnsureName(item, fileInfo);
        }
        /// 
        /// Sets the initial item values.
        /// 
        /// The item.
        /// The args.
        /// The file system.
        /// The library manager.
        public static void SetInitialItemValues(BaseItem item, ItemResolveArgs args, IFileSystem fileSystem, ILibraryManager libraryManager)
        {
            // If the resolver didn't specify this
            if (string.IsNullOrEmpty(item.Path))
            {
                item.Path = args.Path;
            }
            // If the resolver didn't specify this
            if (args.Parent != null)
            {
                item.SetParent(args.Parent);
            }
            item.Id = libraryManager.GetNewItemId(item.Path, item.GetType());
            // Make sure the item has a name
            EnsureName(item, args.FileInfo);
            item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 ||
                item.Parents.Any(i => i.IsLocked);
            // Make sure DateCreated and DateModified have values
            EnsureDates(fileSystem, item, args, true);
        }
        /// 
        /// Ensures the name.
        /// 
        /// The item.
        /// The file information.
        private static void EnsureName(BaseItem item, FileSystemInfo fileInfo)
        {
            // If the subclass didn't supply a name, add it here
            if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(item.Path))
            {
                item.Name = GetDisplayName(fileInfo.Name, (fileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory);
            }
        }
        /// 
        /// Gets the display name.
        /// 
        /// The path.
        /// if set to true [is directory].
        /// System.String.
        private static string GetDisplayName(string path, bool isDirectory)
        {
           return isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path);
        }
        /// 
        /// The MB name regex
        /// 
        private static readonly Regex MbNameRegex = new Regex(@"(\[.*?\])", RegexOptions.Compiled);
        internal static string StripBrackets(string inputString)
        {
            var output = MbNameRegex.Replace(inputString, string.Empty).Trim();
            return Regex.Replace(output, @"\s+", " ");
        }
        /// 
        /// Ensures DateCreated and DateModified have values
        /// 
        /// The file system.
        /// The item.
        /// The args.
        /// if set to true [include creation time].
        private static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            // See if a different path came out of the resolver than what went in
            if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase))
            {
                var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null;
                if (childData != null)
                {
                    if (includeCreationTime)
                    {
                        SetDateCreated(item, fileSystem, childData);
                    }
                    item.DateModified = fileSystem.GetLastWriteTimeUtc(childData);
                }
                else
                {
                    var fileData = fileSystem.GetFileSystemInfo(item.Path);
                    if (fileData.Exists)
                    {
                        if (includeCreationTime)
                        {
                            SetDateCreated(item, fileSystem, fileData);
                        }
                        item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData);
                    }
                }
            }
            else
            {
                if (includeCreationTime)
                {
                    SetDateCreated(item, fileSystem, args.FileInfo);
                }
                item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo);
            }
        }
        private static void SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemInfo info)
        {
            var config = BaseItem.ConfigurationManager.GetMetadataConfiguration();
            if (config.UseFileCreationTimeForDateAdded)
            {
                item.DateCreated = fileSystem.GetCreationTimeUtc(info);
            }
            else
            {
                item.DateCreated = DateTime.UtcNow;
            }
        }
    }
}