using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
using TMDbLib.Objects.General;
namespace MediaBrowser.Providers.Plugins.Tmdb
{
    /// 
    /// Utilities for the TMDb provider.
    /// 
    public static partial class TmdbUtils
    {
        /// 
        /// URL of the TMDb instance to use.
        /// 
        public const string BaseTmdbUrl = "https://www.themoviedb.org/";
        /// 
        /// Name of the provider.
        /// 
        public const string ProviderName = "TheMovieDb";
        /// 
        /// API key to use when performing an API call.
        /// 
        public const string ApiKey = "4219e299c89411838049ab0dab19ebd5";
        /// 
        /// The crew types to keep.
        /// 
        public static readonly string[] WantedCrewTypes =
        {
            PersonType.Director,
            PersonType.Writer,
            PersonType.Producer
        };
        /// 
        /// The crew kinds to keep.
        /// 
        public static readonly PersonKind[] WantedCrewKinds =
        {
            PersonKind.Director,
            PersonKind.Writer,
            PersonKind.Producer
        };
        [GeneratedRegex(@"[\W_-[ยท]]+")]
        private static partial Regex NonWordRegex();
        /// 
        /// Cleans the name according to TMDb requirements.
        /// 
        /// The name of the entity.
        /// The cleaned name.
        public static string CleanName(string name)
        {
            // TMDb expects a space separated list of words make sure that is the case
            return NonWordRegex().Replace(name, " ");
        }
        /// 
        /// Maps the TMDb provided roles for crew members to Jellyfin roles.
        /// 
        /// Crew member to map against the Jellyfin person types.
        /// The Jellyfin person type.
        public static PersonKind MapCrewToPersonType(Crew crew)
        {
            if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase)
                && crew.Job.Contains("director", StringComparison.OrdinalIgnoreCase))
            {
                return PersonKind.Director;
            }
            if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase)
                && crew.Job.Contains("producer", StringComparison.OrdinalIgnoreCase))
            {
                return PersonKind.Producer;
            }
            if (crew.Department.Equals("writing", StringComparison.OrdinalIgnoreCase))
            {
                return PersonKind.Writer;
            }
            return PersonKind.Unknown;
        }
        /// 
        /// Determines whether a video is a trailer.
        /// 
        /// The TMDb video.
        /// A boolean indicating whether the video is a trailer.
        public static bool IsTrailerType(Video video)
        {
            return video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase)
                   && (video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase)
                       || video.Type.Equals("teaser", StringComparison.OrdinalIgnoreCase));
        }
        /// 
        /// Normalizes a language string for use with TMDb's include image language parameter.
        /// 
        /// The preferred language as either a 2 letter code with or without country code.
        /// The country code, ISO 3166-1.
        /// The comma separated language string.
        public static string GetImageLanguagesParam(string preferredLanguage, string? countryCode = null)
        {
            var languages = new List();
            if (!string.IsNullOrEmpty(preferredLanguage))
            {
                preferredLanguage = NormalizeLanguage(preferredLanguage, countryCode);
                languages.Add(preferredLanguage);
                if (preferredLanguage.Length == 5) // Like en-US
                {
                    // Currently, TMDb supports 2-letter language codes only.
                    // They are planning to change this in the future, thus we're
                    // supplying both codes if we're having a 5-letter code.
                    languages.Add(preferredLanguage.Substring(0, 2));
                }
            }
            languages.Add("null");
            // Always add English as fallback language
            if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
            {
                languages.Add("en");
            }
            return string.Join(',', languages);
        }
        /// 
        /// Normalizes a language string for use with TMDb's language parameter.
        /// 
        /// The language code.
        /// The country code.
        /// The normalized language code.
        [return: NotNullIfNotNull(nameof(language))]
        public static string? NormalizeLanguage(string? language, string? countryCode = null)
        {
            if (string.IsNullOrEmpty(language))
            {
                return language;
            }
            // Handle es-419 (Latin American Spanish) by converting to regional variant
            if (string.Equals(language, "es-419", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(countryCode))
            {
                language = string.Equals(countryCode, "AR", StringComparison.OrdinalIgnoreCase)
                    ? "es-AR"
                    : "es-MX";
            }
            // TMDb requires this to be uppercase
            // Everything after the hyphen must be written in uppercase due to a way TMDb wrote their API.
            // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
            var parts = language.Split('-');
            if (parts.Length == 2)
            {
                // TMDb doesn't support Switzerland (de-CH, it-CH or fr-CH) so use the language (de, it or fr) without country code
                if (string.Equals(parts[1], "CH", StringComparison.OrdinalIgnoreCase))
                {
                    return parts[0];
                }
                language = parts[0] + "-" + parts[1].ToUpperInvariant();
            }
            return language;
        }
        /// 
        /// Adjusts the image's language code preferring the 5 letter language code eg. en-US.
        /// 
        /// The image's actual language code.
        /// The requested language code.
        /// The language code.
        public static string AdjustImageLanguage(string imageLanguage, string requestLanguage)
        {
            if (!string.IsNullOrEmpty(imageLanguage)
                && !string.IsNullOrEmpty(requestLanguage)
                && requestLanguage.Length > 2
                && imageLanguage.Length == 2
                && requestLanguage.StartsWith(imageLanguage, StringComparison.OrdinalIgnoreCase))
            {
                return requestLanguage;
            }
            // TMDb now returns xx for no language instead of an empty string.
            return string.Equals(imageLanguage, "xx", StringComparison.OrdinalIgnoreCase)
                ? string.Empty
                : imageLanguage;
        }
        /// 
        /// Combines the metadata country code and the parental rating from the API into the value we store in our database.
        /// 
        /// The ISO 3166-1 country code of the rating country.
        /// The rating value returned by the TMDb API.
        /// The combined parental rating of country code+rating value.
        public static string BuildParentalRating(string countryCode, string ratingValue)
        {
            // Exclude US because we store US values as TV-14 without the country code.
            var ratingPrefix = string.Equals(countryCode, "US", StringComparison.OrdinalIgnoreCase) ? string.Empty : countryCode + "-";
            var newRating = ratingPrefix + ratingValue;
            return newRating.Replace("DE-", "FSK-", StringComparison.OrdinalIgnoreCase);
        }
    }
}