using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Xml;
namespace MediaBrowser.LocalMetadata.Savers
{
    /// 
    /// Class XmlHelpers
    /// 
    public static class XmlSaverHelpers
    {
        private static readonly Dictionary CommonTags = new[] {     
               
                    "Added",
                    "AspectRatio",
                    "AudioDbAlbumId",
                    "AudioDbArtistId",
                    "AwardSummary",
                    "BirthDate",
                    "Budget",
                    
                    // Deprecated. No longer saving in this field.
                    "certification",
                    
                    "Chapters",
                    "ContentRating",
                    "Countries",
                    "CustomRating",
                    "CriticRating",
                    "CriticRatingSummary",
                    "DeathDate",
                    "DisplayOrder",
                    "EndDate",
                    "Genres",
                    "Genre",
                    "GamesDbId",
                    
                    // Deprecated. No longer saving in this field.
                    "IMDB_ID",
                    
                    "IMDB",
                    
                    // Deprecated. No longer saving in this field.
                    "IMDbId",
                    
                    "Language",
                    "LocalTitle",
                    "OriginalTitle",
                    "LockData",
                    "LockedFields",
                    "Format3D",
                    "Metascore",
                    
                    // Deprecated. No longer saving in this field.
                    "MPAARating",
                    "MPAADescription",
                    "MusicBrainzArtistId",
                    "MusicBrainzAlbumArtistId",
                    "MusicBrainzAlbumId",
                    "MusicBrainzReleaseGroupId",
                    // Deprecated. No longer saving in this field.
                    "MusicbrainzId",
                    "Overview",
                    "ShortOverview",
                    "Persons",
                    "PlotKeywords",
                    "PremiereDate",
                    "ProductionYear",
                    "Rating",
                    "Revenue",
                    "RottenTomatoesId",
                    "RunningTime",
                    
                    // Deprecated. No longer saving in this field.
                    "Runtime",
                    
                    "SortTitle",
                    "Studios",
                    "Tags",
                    
                    // Deprecated. No longer saving in this field.
                    "TagLine",
                    "Taglines",
                    "TMDbCollectionId",
                    "TMDbId",
                    // Deprecated. No longer saving in this field.
                    "Trailer",
                    "Trailers",
                    "TVcomId",
                    "TvDbId",
                    "Type",
                    "TVRageId",
                    "VoteCount",
                    "Website",
                    "Zap2ItId",
                    "CollectionItems",
                    "PlaylistItems",
                    "Shares"
        }.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
        /// 
        /// The us culture
        /// 
        private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
        /// 
        /// Saves the specified XML.
        /// 
        /// The XML.
        /// The path.
        /// The XML tags used.
        public static void Save(StringBuilder xml, string path, List xmlTagsUsed, IServerConfigurationManager config)
        {
            if (File.Exists(path))
            {
                var position = xml.ToString().LastIndexOf("", StringComparison.OrdinalIgnoreCase);
                xml.Insert(position, GetCustomTags(path, xmlTagsUsed));
            }
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml.ToString());
            //Add the new node to the document.
            xmlDocument.InsertBefore(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xmlDocument.DocumentElement);
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            var wasHidden = false;
            var file = new FileInfo(path);
            // This will fail if the file is hidden
            if (file.Exists)
            {
                if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    file.Attributes &= ~FileAttributes.Hidden;
                    wasHidden = true;
                }
            }
            using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                using (var streamWriter = new StreamWriter(filestream, Encoding.UTF8))
                {
                    xmlDocument.Save(streamWriter);
                }
            }
            if (wasHidden || config.Configuration.SaveMetadataHidden)
            {
                file.Refresh();
                // Add back the attribute
                file.Attributes |= FileAttributes.Hidden;
            }
        }
        /// 
        /// Gets the custom tags.
        /// 
        /// The path.
        /// The XML tags used.
        /// System.String.
        private static string GetCustomTags(string path, List xmlTagsUsed)
        {
            var settings = new XmlReaderSettings
            {
                CheckCharacters = false,
                IgnoreProcessingInstructions = true,
                IgnoreComments = true,
                ValidationType = ValidationType.None
            };
            var builder = new StringBuilder();
            using (var streamReader = new StreamReader(path, Encoding.UTF8))
            {
                // Use XmlReader for best performance
                using (var reader = XmlReader.Create(streamReader, settings))
                {
                    reader.MoveToContent();
                    // Loop through each element
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            var name = reader.Name;
                            if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
                            {
                                builder.AppendLine(reader.ReadOuterXml());
                            }
                            else
                            {
                                reader.Skip();
                            }
                        }
                    }
                }
            }
            return builder.ToString();
        }
        /// 
        /// Adds the common nodes.
        /// 
        /// The item.
        /// The builder.
        public static void AddCommonNodes(BaseItem item, StringBuilder builder)
        {
            if (!string.IsNullOrEmpty(item.OfficialRating))
            {
                builder.Append("" + SecurityElement.Escape(item.OfficialRating) + "");
            }
            if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
            {
                builder.Append("" + SecurityElement.Escape(item.OfficialRatingDescription) + "");
            }
            builder.Append("" + SecurityElement.Escape(item.DateCreated.ToLocalTime().ToString("G")) + "");
            builder.Append("" + item.IsLocked.ToString().ToLower() + "");
            if (item.LockedFields.Count > 0)
            {
                builder.Append("" + string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()) + "");
            }
            if (!string.IsNullOrEmpty(item.DisplayMediaType))
            {
                builder.Append("" + SecurityElement.Escape(item.DisplayMediaType) + "");
            }
            var hasCriticRating = item as IHasCriticRating;
            if (hasCriticRating != null)
            {
                if (hasCriticRating.CriticRating.HasValue)
                {
                    builder.Append("" + SecurityElement.Escape(hasCriticRating.CriticRating.Value.ToString(UsCulture)) + "");
                }
                if (!string.IsNullOrEmpty(hasCriticRating.CriticRatingSummary))
                {
                    builder.Append("");
                }
            }
            if (!string.IsNullOrEmpty(item.Overview))
            {
                builder.Append("");
            }
            var hasOriginalTitle = item as IHasOriginalTitle;
            if (hasOriginalTitle != null)
            {
                if (!string.IsNullOrEmpty(hasOriginalTitle.OriginalTitle))
                {
                    builder.Append("" + SecurityElement.Escape(hasOriginalTitle.OriginalTitle) + "");
                }
            }
            
            var hasShortOverview = item as IHasShortOverview;
            if (hasShortOverview != null)
            {
                if (!string.IsNullOrEmpty(hasShortOverview.ShortOverview))
                {
                    builder.Append("");
                }
            }
            if (!string.IsNullOrEmpty(item.CustomRating))
            {
                builder.Append("" + SecurityElement.Escape(item.CustomRating) + "");
            }
            if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
            {
                builder.Append("" + SecurityElement.Escape(item.Name) + "");
            }
            if (!string.IsNullOrEmpty(item.ForcedSortName))
            {
                builder.Append("" + SecurityElement.Escape(item.ForcedSortName) + "");
            }
            if (item.PremiereDate.HasValue)
            {
                if (item is Person)
                {
                    builder.Append("" + SecurityElement.Escape(item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd")) + "");
                }
                else if (!(item is Episode))
                {
                    builder.Append("" + SecurityElement.Escape(item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd")) + "");
                }
            }
            if (item.EndDate.HasValue)
            {
                if (item is Person)
                {
                    builder.Append("" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "");
                }
                else if (!(item is Episode))
                {
                    builder.Append("" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "");
                }
            }
            var hasTrailers = item as IHasTrailers;
            if (hasTrailers != null)
            {
                if (hasTrailers.RemoteTrailers.Count > 0)
                {
                    builder.Append("");
                    foreach (var trailer in hasTrailers.RemoteTrailers)
                    {
                        builder.Append("" + SecurityElement.Escape(trailer.Url) + "");
                    }
                    builder.Append("");
                }
            }
            var hasProductionLocations = item as IHasProductionLocations;
            if (hasProductionLocations != null)
            {
                if (hasProductionLocations.ProductionLocations.Count > 0)
                {
                    builder.Append("");
                    foreach (var name in hasProductionLocations.ProductionLocations)
                    {
                        builder.Append("" + SecurityElement.Escape(name) + "");
                    }
                    builder.Append("");
                }
            }
            var hasDisplayOrder = item as IHasDisplayOrder;
            if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
            {
                builder.Append("" + SecurityElement.Escape(hasDisplayOrder.DisplayOrder) + "");
            }
            var hasMetascore = item as IHasMetascore;
            if (hasMetascore != null && hasMetascore.Metascore.HasValue)
            {
                builder.Append("" + SecurityElement.Escape(hasMetascore.Metascore.Value.ToString(UsCulture)) + "");
            }
            var hasAwards = item as IHasAwards;
            if (hasAwards != null && !string.IsNullOrEmpty(hasAwards.AwardSummary))
            {
                builder.Append("" + SecurityElement.Escape(hasAwards.AwardSummary) + "");
            }
            var hasBudget = item as IHasBudget;
            if (hasBudget != null)
            {
                if (hasBudget.Budget.HasValue)
                {
                    builder.Append("" + SecurityElement.Escape(hasBudget.Budget.Value.ToString(UsCulture)) + "");
                }
                if (hasBudget.Revenue.HasValue)
                {
                    builder.Append("" + SecurityElement.Escape(hasBudget.Revenue.Value.ToString(UsCulture)) + "");
                }
            }
            if (item.CommunityRating.HasValue)
            {
                builder.Append("" + SecurityElement.Escape(item.CommunityRating.Value.ToString(UsCulture)) + "");
            }
            if (item.VoteCount.HasValue)
            {
                builder.Append("" + SecurityElement.Escape(item.VoteCount.Value.ToString(UsCulture)) + "");
            }
            if (item.ProductionYear.HasValue && !(item is Person))
            {
                builder.Append("" + SecurityElement.Escape(item.ProductionYear.Value.ToString(UsCulture)) + "");
            }
            if (!string.IsNullOrEmpty(item.HomePageUrl))
            {
                builder.Append("" + SecurityElement.Escape(item.HomePageUrl) + "");
            }
            var hasAspectRatio = item as IHasAspectRatio;
            if (hasAspectRatio != null)
            {
                if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
                {
                    builder.Append("" + SecurityElement.Escape(hasAspectRatio.AspectRatio) + "");
                }
            }
            var hasLanguage = item as IHasPreferredMetadataLanguage;
            if (hasLanguage != null)
            {
                if (!string.IsNullOrEmpty(hasLanguage.PreferredMetadataLanguage))
                {
                    builder.Append("" + SecurityElement.Escape(hasLanguage.PreferredMetadataLanguage) + "");
                }
                if (!string.IsNullOrEmpty(hasLanguage.PreferredMetadataCountryCode))
                {
                    builder.Append("" + SecurityElement.Escape(hasLanguage.PreferredMetadataCountryCode) + "");
                }
            }
            // Use original runtime here, actual file runtime later in MediaInfo
            var runTimeTicks = item.RunTimeTicks;
            if (runTimeTicks.HasValue)
            {
                var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
                builder.Append("" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "");
            }
            var imdb = item.GetProviderId(MetadataProviders.Imdb);
            if (!string.IsNullOrEmpty(imdb))
            {
                builder.Append("" + SecurityElement.Escape(imdb) + "");
            }
            var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
            if (!string.IsNullOrEmpty(tmdb))
            {
                builder.Append("" + SecurityElement.Escape(tmdb) + "");
            }
            if (!(item is Series))
            {
                var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
                if (!string.IsNullOrEmpty(tvdb))
                {
                    builder.Append("" + SecurityElement.Escape(tvdb) + "");
                }
            }
            var externalId = item.GetProviderId(MetadataProviders.Tvcom);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.RottenTomatoes);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.Zap2It);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbum);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.MusicBrainzArtist);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.Gamesdb);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.TmdbCollection);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.AudioDbArtist);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.AudioDbAlbum);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            externalId = item.GetProviderId(MetadataProviders.TvRage);
            if (!string.IsNullOrEmpty(externalId))
            {
                builder.Append("" + SecurityElement.Escape(externalId) + "");
            }
            var hasTagline = item as IHasTaglines;
            if (hasTagline != null)
            {
                if (hasTagline.Taglines.Count > 0)
                {
                    builder.Append("");
                    foreach (var tagline in hasTagline.Taglines)
                    {
                        builder.Append("" + SecurityElement.Escape(tagline) + "");
                    }
                    builder.Append("");
                }
            }
            if (item.Genres.Count > 0)
            {
                builder.Append("");
                foreach (var genre in item.Genres)
                {
                    builder.Append("" + SecurityElement.Escape(genre) + "");
                }
                builder.Append("");
            }
            if (item.Studios.Count > 0)
            {
                builder.Append("");
                foreach (var studio in item.Studios)
                {
                    builder.Append("" + SecurityElement.Escape(studio) + "");
                }
                builder.Append("");
            }
            var hasTags = item as IHasTags;
            if (hasTags != null)
            {
                if (hasTags.Tags.Count > 0)
                {
                    builder.Append("");
                    foreach (var tag in hasTags.Tags)
                    {
                        builder.Append("" + SecurityElement.Escape(tag) + "");
                    }
                    builder.Append("");
                }
            }
            var hasKeywords = item as IHasKeywords;
            if (hasKeywords != null)
            {
                if (hasKeywords.Keywords.Count > 0)
                {
                    builder.Append("");
                    foreach (var tag in hasKeywords.Keywords)
                    {
                        builder.Append("" + SecurityElement.Escape(tag) + "");
                    }
                    builder.Append("");
                }
            }
            if (item.People.Count > 0)
            {
                builder.Append("");
                foreach (var person in item.People)
                {
                    builder.Append("");
                    builder.Append("" + SecurityElement.Escape(person.Name) + "");
                    builder.Append("" + SecurityElement.Escape(person.Type) + "");
                    builder.Append("" + SecurityElement.Escape(person.Role) + "");
                    if (person.SortOrder.HasValue)
                    {
                        builder.Append("" + SecurityElement.Escape(person.SortOrder.Value.ToString(UsCulture)) + "");
                    }
                    builder.Append("");
                }
                builder.Append("");
            }
            var boxset = item as BoxSet;
            if (boxset != null)
            {
                AddLinkedChildren(boxset, builder, "CollectionItems", "CollectionItem");
            }
            var playlist = item as Playlist;
            if (playlist != null)
            {
                AddLinkedChildren(playlist, builder, "PlaylistItems", "PlaylistItem");
            }
            var hasShares = item as IHasShares;
            if (hasShares != null)
            {
                AddShares(hasShares, builder);
            }
        }
        public static void AddShares(IHasShares item, StringBuilder builder)
        {
            builder.Append("");
            foreach (var share in item.Shares)
            {
                builder.Append("");
                builder.Append("" + SecurityElement.Escape(share.UserId) + "");
                builder.Append("" + SecurityElement.Escape(share.CanEdit.ToString().ToLower()) + "");
                builder.Append("");
            }
            builder.Append("");
        }
        public static void AddChapters(Video item, StringBuilder builder, IItemRepository repository)
        {
            var chapters = repository.GetChapters(item.Id);
            builder.Append("");
            foreach (var chapter in chapters)
            {
                builder.Append("");
                builder.Append("" + SecurityElement.Escape(chapter.Name) + "");
                var time = TimeSpan.FromTicks(chapter.StartPositionTicks);
                var ms = Convert.ToInt64(time.TotalMilliseconds);
                builder.Append("" + SecurityElement.Escape(ms.ToString(UsCulture)) + "");
                builder.Append("");
            }
            builder.Append("");
        }
        /// 
        /// Appends the media info.
        /// 
        /// 
        public static void AddMediaInfo(T item, StringBuilder builder, IItemRepository itemRepository)
            where T : BaseItem
        {
            var video = item as Video;
            if (video != null)
            {
                //AddChapters(video, builder, itemRepository);
                if (video.Video3DFormat.HasValue)
                {
                    switch (video.Video3DFormat.Value)
                    {
                        case Video3DFormat.FullSideBySide:
                            builder.Append("FSBS");
                            break;
                        case Video3DFormat.FullTopAndBottom:
                            builder.Append("FTAB");
                            break;
                        case Video3DFormat.HalfSideBySide:
                            builder.Append("HSBS");
                            break;
                        case Video3DFormat.HalfTopAndBottom:
                            builder.Append("HTAB");
                            break;
                    }
                }
            }
        }
        public static void AddLinkedChildren(Folder item, StringBuilder builder, string pluralNodeName, string singularNodeName)
        {
            var items = item.LinkedChildren
                .Where(i => i.Type == LinkedChildType.Manual)
                .ToList();
            if (items.Count == 0)
            {
                return;
            }
            builder.Append("<" + pluralNodeName + ">");
            foreach (var link in items)
            {
                builder.Append("<" + singularNodeName + ">");
                if (!string.IsNullOrWhiteSpace(link.Path))
                {
                    builder.Append("" + SecurityElement.Escape((link.Path)) + "");
                }
                builder.Append("" + singularNodeName + ">");
            }
            builder.Append("" + pluralNodeName + ">");
        }
    }
}