using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
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 artists controller.
/// 
[Route("Artists")]
[Authorize]
public class ArtistsController : BaseJellyfinApiController
{
    private readonly ILibraryManager _libraryManager;
    private readonly IUserManager _userManager;
    private readonly IDtoService _dtoService;
    /// 
    /// Initializes a new instance of the  class.
    /// 
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    public ArtistsController(
        ILibraryManager libraryManager,
        IUserManager userManager,
        IDtoService dtoService)
    {
        _libraryManager = libraryManager;
        _userManager = userManager;
        _dtoService = dtoService;
    }
    /// 
    /// Gets all artists from a given item, folder, or the entire library.
    /// 
    /// Optional filter by minimum community rating.
    /// 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.
    /// Optional. 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 based on item type. This allows multiple, comma delimited.
    /// Optional. Specify additional filters to apply.
    /// Optional filter by items that are marked as favorite, or not.
    /// Optional filter by MediaType. Allows multiple, comma delimited.
    /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
    /// Optional, include user data.
    /// Optional, the max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// Optional. If specified, results will be filtered to include only those containing the specified person.
    /// Optional. If specified, results will be filtered to include only those containing the specified person ids.
    /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
    /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
    /// 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. Specify one or more sort orders, comma delimited.
    /// Sort Order - Ascending,Descending.
    /// Optional, include image information in output.
    /// Total record count.
    /// Artists returned.
    /// An  containing the artists.
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult> GetArtists(
        [FromQuery] double? minCommunityRating,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery] string? searchTerm,
        [FromQuery] Guid? parentId,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] excludeItemTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] includeItemTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFilter[] filters,
        [FromQuery] bool? isFavorite,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] MediaType[] mediaTypes,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] genres,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] genreIds,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] officialRatings,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] tags,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] int[] years,
        [FromQuery] bool? enableUserData,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery] string? person,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] personIds,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] string[] personTypes,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] studios,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] studioIds,
        [FromQuery] Guid? userId,
        [FromQuery] string? nameStartsWithOrGreater,
        [FromQuery] string? nameStartsWith,
        [FromQuery] string? nameLessThan,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemSortBy[] sortBy,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] SortOrder[] sortOrder,
        [FromQuery] bool? enableImages = true,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        User? user = null;
        BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId);
        if (!userId.IsNullOrEmpty())
        {
            user = _userManager.GetUserById(userId.Value);
        }
        var query = new InternalItemsQuery(user)
        {
            ExcludeItemTypes = excludeItemTypes,
            IncludeItemTypes = includeItemTypes,
            MediaTypes = mediaTypes,
            StartIndex = startIndex,
            Limit = limit,
            IsFavorite = isFavorite,
            NameLessThan = nameLessThan,
            NameStartsWith = nameStartsWith,
            NameStartsWithOrGreater = nameStartsWithOrGreater,
            Tags = tags,
            OfficialRatings = officialRatings,
            Genres = genres,
            GenreIds = genreIds,
            StudioIds = studioIds,
            Person = person,
            PersonIds = personIds,
            PersonTypes = personTypes,
            Years = years,
            MinCommunityRating = minCommunityRating,
            DtoOptions = dtoOptions,
            SearchTerm = searchTerm,
            EnableTotalRecordCount = enableTotalRecordCount,
            OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
        };
        if (parentId.HasValue)
        {
            if (parentItem is Folder)
            {
                query.AncestorIds = new[] { parentId.Value };
            }
            else
            {
                query.ItemIds = new[] { parentId.Value };
            }
        }
        // Studios
        if (studios.Length != 0)
        {
            query.StudioIds = studios.Select(i =>
            {
                try
                {
                    return _libraryManager.GetStudio(i);
                }
                catch
                {
                    return null;
                }
            }).Where(i => i is not null).Select(i => i!.Id).ToArray();
        }
        foreach (var filter in filters)
        {
            switch (filter)
            {
                case ItemFilter.Dislikes:
                    query.IsLiked = false;
                    break;
                case ItemFilter.IsFavorite:
                    query.IsFavorite = true;
                    break;
                case ItemFilter.IsFavoriteOrLikes:
                    query.IsFavoriteOrLiked = true;
                    break;
                case ItemFilter.IsFolder:
                    query.IsFolder = true;
                    break;
                case ItemFilter.IsNotFolder:
                    query.IsFolder = false;
                    break;
                case ItemFilter.IsPlayed:
                    query.IsPlayed = true;
                    break;
                case ItemFilter.IsResumable:
                    query.IsResumable = true;
                    break;
                case ItemFilter.IsUnplayed:
                    query.IsPlayed = false;
                    break;
                case ItemFilter.Likes:
                    query.IsLiked = true;
                    break;
            }
        }
        var result = _libraryManager.GetArtists(query);
        var dtos = result.Items.Select(i =>
        {
            var (baseItem, itemCounts) = i;
            var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
            if (includeItemTypes.Length != 0)
            {
                dto.ChildCount = itemCounts.ItemCount;
                dto.ProgramCount = itemCounts.ProgramCount;
                dto.SeriesCount = itemCounts.SeriesCount;
                dto.EpisodeCount = itemCounts.EpisodeCount;
                dto.MovieCount = itemCounts.MovieCount;
                dto.TrailerCount = itemCounts.TrailerCount;
                dto.AlbumCount = itemCounts.AlbumCount;
                dto.SongCount = itemCounts.SongCount;
                dto.ArtistCount = itemCounts.ArtistCount;
            }
            return dto;
        });
        return new QueryResult(
            query.StartIndex,
            result.TotalRecordCount,
            dtos.ToArray());
    }
    /// 
    /// Gets all album artists from a given item, folder, or the entire library.
    /// 
    /// Optional filter by minimum community rating.
    /// 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.
    /// Optional. 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 based on item type. This allows multiple, comma delimited.
    /// Optional. Specify additional filters to apply.
    /// Optional filter by items that are marked as favorite, or not.
    /// Optional filter by MediaType. Allows multiple, comma delimited.
    /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
    /// Optional, include user data.
    /// Optional, the max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// Optional. If specified, results will be filtered to include only those containing the specified person.
    /// Optional. If specified, results will be filtered to include only those containing the specified person ids.
    /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
    /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
    /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
    /// 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. Specify one or more sort orders, comma delimited.
    /// Sort Order - Ascending,Descending.
    /// Optional, include image information in output.
    /// Total record count.
    /// Album artists returned.
    /// An  containing the album artists.
    [HttpGet("AlbumArtists")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult> GetAlbumArtists(
        [FromQuery] double? minCommunityRating,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery] string? searchTerm,
        [FromQuery] Guid? parentId,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] excludeItemTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] includeItemTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFilter[] filters,
        [FromQuery] bool? isFavorite,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] MediaType[] mediaTypes,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] genres,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] genreIds,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] officialRatings,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] tags,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] int[] years,
        [FromQuery] bool? enableUserData,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery] string? person,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] personIds,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] string[] personTypes,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] studios,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] studioIds,
        [FromQuery] Guid? userId,
        [FromQuery] string? nameStartsWithOrGreater,
        [FromQuery] string? nameStartsWith,
        [FromQuery] string? nameLessThan,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemSortBy[] sortBy,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] SortOrder[] sortOrder,
        [FromQuery] bool? enableImages = true,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        User? user = null;
        BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId);
        if (!userId.IsNullOrEmpty())
        {
            user = _userManager.GetUserById(userId.Value);
        }
        var query = new InternalItemsQuery(user)
        {
            ExcludeItemTypes = excludeItemTypes,
            IncludeItemTypes = includeItemTypes,
            MediaTypes = mediaTypes,
            StartIndex = startIndex,
            Limit = limit,
            IsFavorite = isFavorite,
            NameLessThan = nameLessThan,
            NameStartsWith = nameStartsWith,
            NameStartsWithOrGreater = nameStartsWithOrGreater,
            Tags = tags,
            OfficialRatings = officialRatings,
            Genres = genres,
            GenreIds = genreIds,
            StudioIds = studioIds,
            Person = person,
            PersonIds = personIds,
            PersonTypes = personTypes,
            Years = years,
            MinCommunityRating = minCommunityRating,
            DtoOptions = dtoOptions,
            SearchTerm = searchTerm,
            EnableTotalRecordCount = enableTotalRecordCount,
            OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
        };
        if (parentId.HasValue)
        {
            if (parentItem is Folder)
            {
                query.AncestorIds = new[] { parentId.Value };
            }
            else
            {
                query.ItemIds = new[] { parentId.Value };
            }
        }
        // Studios
        if (studios.Length != 0)
        {
            query.StudioIds = studios.Select(i =>
            {
                try
                {
                    return _libraryManager.GetStudio(i);
                }
                catch
                {
                    return null;
                }
            }).Where(i => i is not null).Select(i => i!.Id).ToArray();
        }
        foreach (var filter in filters)
        {
            switch (filter)
            {
                case ItemFilter.Dislikes:
                    query.IsLiked = false;
                    break;
                case ItemFilter.IsFavorite:
                    query.IsFavorite = true;
                    break;
                case ItemFilter.IsFavoriteOrLikes:
                    query.IsFavoriteOrLiked = true;
                    break;
                case ItemFilter.IsFolder:
                    query.IsFolder = true;
                    break;
                case ItemFilter.IsNotFolder:
                    query.IsFolder = false;
                    break;
                case ItemFilter.IsPlayed:
                    query.IsPlayed = true;
                    break;
                case ItemFilter.IsResumable:
                    query.IsResumable = true;
                    break;
                case ItemFilter.IsUnplayed:
                    query.IsPlayed = false;
                    break;
                case ItemFilter.Likes:
                    query.IsLiked = true;
                    break;
            }
        }
        var result = _libraryManager.GetAlbumArtists(query);
        var dtos = result.Items.Select(i =>
        {
            var (baseItem, itemCounts) = i;
            var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
            if (includeItemTypes.Length != 0)
            {
                dto.ChildCount = itemCounts.ItemCount;
                dto.ProgramCount = itemCounts.ProgramCount;
                dto.SeriesCount = itemCounts.SeriesCount;
                dto.EpisodeCount = itemCounts.EpisodeCount;
                dto.MovieCount = itemCounts.MovieCount;
                dto.TrailerCount = itemCounts.TrailerCount;
                dto.AlbumCount = itemCounts.AlbumCount;
                dto.SongCount = itemCounts.SongCount;
                dto.ArtistCount = itemCounts.ArtistCount;
            }
            return dto;
        });
        return new QueryResult(
            query.StartIndex,
            result.TotalRecordCount,
            dtos.ToArray());
    }
    /// 
    /// Gets an artist by name.
    /// 
    /// Studio name.
    /// Optional. Filter by user id, and attach user data.
    /// Artist returned.
    /// An  containing the artist.
    [HttpGet("{name}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult GetArtistByName([FromRoute, Required] string name, [FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var dtoOptions = new DtoOptions().AddClientFields(User);
        var item = _libraryManager.GetArtist(name, dtoOptions);
        if (!userId.IsNullOrEmpty())
        {
            var user = _userManager.GetUserById(userId.Value);
            return _dtoService.GetBaseItemDto(item, dtoOptions, user);
        }
        return _dtoService.GetBaseItemDto(item, dtoOptions);
    }
}