using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Session;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.Controllers
{
    /// 
    /// Playstate controller.
    /// 
    [Route("")]
    [Authorize(Policy = Policies.DefaultAuthorization)]
    public class PlaystateController : BaseJellyfinApiController
    {
        private readonly IUserManager _userManager;
        private readonly IUserDataManager _userDataRepository;
        private readonly ILibraryManager _libraryManager;
        private readonly ISessionManager _sessionManager;
        private readonly IAuthorizationContext _authContext;
        private readonly ILogger _logger;
        private readonly TranscodingJobHelper _transcodingJobHelper;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// Instance of the  interface.
        /// Instance of the  interface.
        /// Instance of the  interface.
        /// Instance of the  interface.
        /// Instance of the  interface.
        /// Instance of the  interface.
        /// Th  singleton.
        public PlaystateController(
            IUserManager userManager,
            IUserDataManager userDataRepository,
            ILibraryManager libraryManager,
            ISessionManager sessionManager,
            IAuthorizationContext authContext,
            ILoggerFactory loggerFactory,
            TranscodingJobHelper transcodingJobHelper)
        {
            _userManager = userManager;
            _userDataRepository = userDataRepository;
            _libraryManager = libraryManager;
            _sessionManager = sessionManager;
            _authContext = authContext;
            _logger = loggerFactory.CreateLogger();
            _transcodingJobHelper = transcodingJobHelper;
        }
        /// 
        /// Marks an item as played for user.
        /// 
        /// User id.
        /// Item id.
        /// Optional. The date the item was played.
        /// Item marked as played.
        /// An  containing the .
        [HttpPost("Users/{userId}/PlayedItems/{itemId}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task> MarkPlayedItem(
            [FromRoute, Required] Guid userId,
            [FromRoute, Required] Guid itemId,
            [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed)
        {
            var user = _userManager.GetUserById(userId);
            var session = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
            var dto = UpdatePlayedStatus(user, itemId, true, datePlayed);
            foreach (var additionalUserInfo in session.AdditionalUsers)
            {
                var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
                UpdatePlayedStatus(additionalUser, itemId, true, datePlayed);
            }
            return dto;
        }
        /// 
        /// Marks an item as unplayed for user.
        /// 
        /// User id.
        /// Item id.
        /// Item marked as unplayed.
        /// A  containing the .
        [HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task> MarkUnplayedItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
        {
            var user = _userManager.GetUserById(userId);
            var session = await RequestHelpers.GetSession(_sessionManager, _authContext, Request).ConfigureAwait(false);
            var dto = UpdatePlayedStatus(user, itemId, false, null);
            foreach (var additionalUserInfo in session.AdditionalUsers)
            {
                var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
                UpdatePlayedStatus(additionalUser, itemId, false, null);
            }
            return dto;
        }
        /// 
        /// Reports playback has started within a session.
        /// 
        /// The playback start info.
        /// Playback start recorded.
        /// A .
        [HttpPost("Sessions/Playing")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public async Task ReportPlaybackStart([FromBody] PlaybackStartInfo playbackStartInfo)
        {
            playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
            playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Reports playback progress within a session.
        /// 
        /// The playback progress info.
        /// Playback progress recorded.
        /// A .
        [HttpPost("Sessions/Playing/Progress")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public async Task ReportPlaybackProgress([FromBody] PlaybackProgressInfo playbackProgressInfo)
        {
            playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
            playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Pings a playback session.
        /// 
        /// Playback session id.
        /// Playback session pinged.
        /// A .
        [HttpPost("Sessions/Playing/Ping")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult PingPlaybackSession([FromQuery, Required] string playSessionId)
        {
            _transcodingJobHelper.PingTranscodingJob(playSessionId, null);
            return NoContent();
        }
        /// 
        /// Reports playback has stopped within a session.
        /// 
        /// The playback stop info.
        /// Playback stop recorded.
        /// A .
        [HttpPost("Sessions/Playing/Stopped")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public async Task ReportPlaybackStopped([FromBody] PlaybackStopInfo playbackStopInfo)
        {
            _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
            if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
            {
                var authInfo = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
                await _transcodingJobHelper.KillTranscodingJobs(authInfo.DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
            }
            playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Reports that a user has begun playing an item.
        /// 
        /// User id.
        /// Item id.
        /// The id of the MediaSource.
        /// The audio stream index.
        /// The subtitle stream index.
        /// The play method.
        /// The live stream id.
        /// The play session id.
        /// Indicates if the client can seek.
        /// Play start recorded.
        /// A .
        [HttpPost("Users/{userId}/PlayingItems/{itemId}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
        public async Task OnPlaybackStart(
            [FromRoute, Required] Guid userId,
            [FromRoute, Required] Guid itemId,
            [FromQuery] string? mediaSourceId,
            [FromQuery] int? audioStreamIndex,
            [FromQuery] int? subtitleStreamIndex,
            [FromQuery] PlayMethod? playMethod,
            [FromQuery] string? liveStreamId,
            [FromQuery] string? playSessionId,
            [FromQuery] bool canSeek = false)
        {
            var playbackStartInfo = new PlaybackStartInfo
            {
                CanSeek = canSeek,
                ItemId = itemId,
                MediaSourceId = mediaSourceId,
                AudioStreamIndex = audioStreamIndex,
                SubtitleStreamIndex = subtitleStreamIndex,
                PlayMethod = playMethod ?? PlayMethod.Transcode,
                PlaySessionId = playSessionId,
                LiveStreamId = liveStreamId
            };
            playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
            playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Reports a user's playback progress.
        /// 
        /// User id.
        /// Item id.
        /// The id of the MediaSource.
        /// Optional. The current position, in ticks. 1 tick = 10000 ms.
        /// The audio stream index.
        /// The subtitle stream index.
        /// Scale of 0-100.
        /// The play method.
        /// The live stream id.
        /// The play session id.
        /// The repeat mode.
        /// Indicates if the player is paused.
        /// Indicates if the player is muted.
        /// Play progress recorded.
        /// A .
        [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
        public async Task OnPlaybackProgress(
            [FromRoute, Required] Guid userId,
            [FromRoute, Required] Guid itemId,
            [FromQuery] string? mediaSourceId,
            [FromQuery] long? positionTicks,
            [FromQuery] int? audioStreamIndex,
            [FromQuery] int? subtitleStreamIndex,
            [FromQuery] int? volumeLevel,
            [FromQuery] PlayMethod? playMethod,
            [FromQuery] string? liveStreamId,
            [FromQuery] string? playSessionId,
            [FromQuery] RepeatMode? repeatMode,
            [FromQuery] bool isPaused = false,
            [FromQuery] bool isMuted = false)
        {
            var playbackProgressInfo = new PlaybackProgressInfo
            {
                ItemId = itemId,
                PositionTicks = positionTicks,
                IsMuted = isMuted,
                IsPaused = isPaused,
                MediaSourceId = mediaSourceId,
                AudioStreamIndex = audioStreamIndex,
                SubtitleStreamIndex = subtitleStreamIndex,
                VolumeLevel = volumeLevel,
                PlayMethod = playMethod ?? PlayMethod.Transcode,
                PlaySessionId = playSessionId,
                LiveStreamId = liveStreamId,
                RepeatMode = repeatMode ?? RepeatMode.RepeatNone
            };
            playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
            playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Reports that a user has stopped playing an item.
        /// 
        /// User id.
        /// Item id.
        /// The id of the MediaSource.
        /// The next media type that will play.
        /// Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.
        /// The live stream id.
        /// The play session id.
        /// Playback stop recorded.
        /// A .
        [HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
        public async Task OnPlaybackStopped(
            [FromRoute, Required] Guid userId,
            [FromRoute, Required] Guid itemId,
            [FromQuery] string? mediaSourceId,
            [FromQuery] string? nextMediaType,
            [FromQuery] long? positionTicks,
            [FromQuery] string? liveStreamId,
            [FromQuery] string? playSessionId)
        {
            var playbackStopInfo = new PlaybackStopInfo
            {
                ItemId = itemId,
                PositionTicks = positionTicks,
                MediaSourceId = mediaSourceId,
                PlaySessionId = playSessionId,
                LiveStreamId = liveStreamId,
                NextMediaType = nextMediaType
            };
            _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
            if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
            {
                var authInfo = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
                await _transcodingJobHelper.KillTranscodingJobs(authInfo.DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
            }
            playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _authContext, Request).ConfigureAwait(false);
            await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
            return NoContent();
        }
        /// 
        /// Updates the played status.
        /// 
        /// The user.
        /// The item id.
        /// if set to true [was played].
        /// The date played.
        /// Task.
        private UserItemDataDto UpdatePlayedStatus(User user, Guid itemId, bool wasPlayed, DateTime? datePlayed)
        {
            var item = _libraryManager.GetItemById(itemId);
            if (wasPlayed)
            {
                item.MarkPlayed(user, datePlayed, true);
            }
            else
            {
                item.MarkUnplayed(user);
            }
            return _userDataRepository.GetUserDataDto(item, user);
        }
        private PlayMethod ValidatePlayMethod(PlayMethod method, string? playSessionId)
        {
            if (method == PlayMethod.Transcode)
            {
                var job = string.IsNullOrWhiteSpace(playSessionId) ? null : _transcodingJobHelper.GetTranscodingJob(playSessionId);
                if (job == null)
                {
                    return PlayMethod.DirectPlay;
                }
            }
            return method;
        }
    }
}