using System;
using System.Net.Mime;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Model.Globalization;
using Microsoft.AspNetCore.Http;
namespace Jellyfin.Server.Middleware
{
    /// 
    /// Shows a custom message during server startup.
    /// 
    public class ServerStartupMessageMiddleware
    {
        private readonly RequestDelegate _next;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The next delegate in the pipeline.
        public ServerStartupMessageMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// 
        /// Executes the middleware action.
        /// 
        /// The current HTTP context.
        /// The server application host.
        /// The localization manager.
        /// The async task.
        public async Task Invoke(
            HttpContext httpContext,
            IServerApplicationHost serverApplicationHost,
            ILocalizationManager localizationManager)
        {
            if (serverApplicationHost.CoreStartupHasCompleted
                || httpContext.Request.Path.Equals("/system/ping", StringComparison.OrdinalIgnoreCase))
            {
                await _next(httpContext).ConfigureAwait(false);
                return;
            }
            var message = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
            httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
            httpContext.Response.ContentType = MediaTypeNames.Text.Html;
            await httpContext.Response.WriteAsync(message, httpContext.RequestAborted).ConfigureAwait(false);
        }
    }
}