using System;
using System.Collections.Generic;
using System.Globalization;
namespace MediaBrowser.MediaEncoding.Probing
{
    /// 
    /// Class containing helper methods for working with FFprobe output.
    /// 
    public static class FFProbeHelpers
    {
        /// 
        /// Normalizes the FF probe result.
        /// 
        /// The result.
        public static void NormalizeFFProbeResult(InternalMediaInfoResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }
            if (result.Format?.Tags != null)
            {
                result.Format.Tags = ConvertDictionaryToCaseInsensitive(result.Format.Tags);
            }
            if (result.Streams != null)
            {
                // Convert all dictionaries to case insensitive
                foreach (var stream in result.Streams)
                {
                    if (stream.Tags != null)
                    {
                        stream.Tags = ConvertDictionaryToCaseInsensitive(stream.Tags);
                    }
                }
            }
        }
        /// 
        /// Gets an int from an FFProbeResult tags dictionary.
        /// 
        /// The tags.
        /// The key.
        /// System.Nullable{System.Int32}.
        public static int? GetDictionaryNumericValue(IReadOnlyDictionary tags, string key)
        {
            if (tags.TryGetValue(key, out var val) && int.TryParse(val, out var i))
            {
                return i;
            }
            return null;
        }
        /// 
        /// Gets a DateTime from an FFProbeResult tags dictionary.
        /// 
        /// The tags.
        /// The key.
        /// System.Nullable{DateTime}.
        public static DateTime? GetDictionaryDateTime(IReadOnlyDictionary tags, string key)
        {
            if (tags.TryGetValue(key, out var val)
                && (DateTime.TryParse(val, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var dateTime)
                    || DateTime.TryParseExact(val, "yyyy", DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out dateTime)))
            {
                return dateTime;
            }
            return null;
        }
        /// 
        /// Converts a dictionary to case insensitive.
        /// 
        /// The dict.
        /// Dictionary{System.StringSystem.String}.
        private static Dictionary ConvertDictionaryToCaseInsensitive(IReadOnlyDictionary dict)
        {
            return new Dictionary(dict, StringComparer.OrdinalIgnoreCase);
        }
    }
}