using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers
{
    /// 
    /// The music genres controller.
    /// 
    [Authorize(Policy = Policies.DefaultAuthorization)]
    public class MusicGenresController : BaseJellyfinApiController
    {
        private readonly ILibraryManager _libraryManager;
        private readonly IDtoService _dtoService;
        private readonly IUserManager _userManager;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// Instance of  interface.
        /// Instance of  interface.
        /// Instance of  interface.
        public MusicGenresController(
            ILibraryManager libraryManager,
            IUserManager userManager,
            IDtoService dtoService)
        {
            _libraryManager = libraryManager;
            _userManager = userManager;
            _dtoService = dtoService;
        }
        /// 
        /// Gets all music genres from a given item, folder, or the entire library.
        /// 
        /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
        /// Optional. The maximum number of records to return.
        /// The search term.
        /// Specify this to localize the search to a specific item or folder. Omit to use the root.
        /// Optional. Specify additional fields of information to return in the output.
        /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.
        /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.
        /// Optional filter by items that are marked as favorite, or not.
        /// Optional, the max number of images to return, per image type.
        /// Optional. The image types to include in the output.
        /// User id.
        /// Optional filter by items whose name is sorted equally or greater than a given input string.
        /// Optional filter by items whose name is sorted equally than a given input string.
        /// Optional filter by items whose name is equally or lesser than a given input string.
        /// Optional, include image information in output.
        /// Optional. Include total record count.
        /// Music genres returned.
        /// An  containing the queryresult of music genres.
        [HttpGet]
        [Obsolete("Use GetGenres instead")]
        public ActionResult> GetMusicGenres(
            [FromQuery] int? startIndex,
            [FromQuery] int? limit,
            [FromQuery] string? searchTerm,
            [FromQuery] Guid? parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes,
            [FromQuery] bool? isFavorite,
            [FromQuery] int? imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] Guid? userId,
            [FromQuery] string? nameStartsWithOrGreater,
            [FromQuery] string? nameStartsWith,
            [FromQuery] string? nameLessThan,
            [FromQuery] bool? enableImages = true,
            [FromQuery] bool enableTotalRecordCount = true)
        {
            var dtoOptions = new DtoOptions { Fields = fields }
                .AddClientFields(Request)
                .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
            User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
            var parentItem = _libraryManager.GetParentItem(parentId, userId);
            var query = new InternalItemsQuery(user)
            {
                ExcludeItemTypes = excludeItemTypes,
                IncludeItemTypes = includeItemTypes,
                StartIndex = startIndex,
                Limit = limit,
                IsFavorite = isFavorite,
                NameLessThan = nameLessThan,
                NameStartsWith = nameStartsWith,
                NameStartsWithOrGreater = nameStartsWithOrGreater,
                DtoOptions = dtoOptions,
                SearchTerm = searchTerm,
                EnableTotalRecordCount = enableTotalRecordCount
            };
            if (parentId.HasValue)
            {
                if (parentItem is Folder)
                {
                    query.AncestorIds = new[] { parentId.Value };
                }
                else
                {
                    query.ItemIds = new[] { parentId.Value };
                }
            }
            var result = _libraryManager.GetMusicGenres(query);
            var shouldIncludeItemTypes = includeItemTypes.Length != 0;
            return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
        }
        /// 
        /// Gets a music genre, by name.
        /// 
        /// The genre name.
        /// Optional. Filter by user id, and attach user data.
        /// An  containing a  with the music genre.
        [HttpGet("{genreName}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult GetMusicGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
        {
            var dtoOptions = new DtoOptions().AddClientFields(Request);
            MusicGenre? item;
            if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1)
            {
                item = GetItemFromSlugName(_libraryManager, genreName, dtoOptions);
            }
            else
            {
                item = _libraryManager.GetMusicGenre(genreName);
            }
            if (userId.HasValue && !userId.Equals(Guid.Empty))
            {
                var user = _userManager.GetUserById(userId.Value);
                return _dtoService.GetBaseItemDto(item, dtoOptions, user);
            }
            return _dtoService.GetBaseItemDto(item, dtoOptions);
        }
        private T? GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
            where T : BaseItem, new()
        {
            var result = libraryManager.GetItemList(new InternalItemsQuery
            {
                Name = name.Replace(BaseItem.SlugChar, '&'),
                IncludeItemTypes = new[] { typeof(T).Name },
                DtoOptions = dtoOptions
            }).OfType().FirstOrDefault();
            result ??= libraryManager.GetItemList(new InternalItemsQuery
            {
                Name = name.Replace(BaseItem.SlugChar, '/'),
                IncludeItemTypes = new[] { typeof(T).Name },
                DtoOptions = dtoOptions
            }).OfType().FirstOrDefault();
            result ??= libraryManager.GetItemList(new InternalItemsQuery
            {
                Name = name.Replace(BaseItem.SlugChar, '?'),
                IncludeItemTypes = new[] { typeof(T).Name },
                DtoOptions = dtoOptions
            }).OfType().FirstOrDefault();
            return result;
        }
    }
}