using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Http;
namespace Jellyfin.Server.Middleware
{
    /// 
    /// Validates the IP of requests coming from local networks wrt. remote access.
    /// 
    public class IpBasedAccessValidationMiddleware
    {
        private readonly RequestDelegate _next;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The next delegate in the pipeline.
        public IpBasedAccessValidationMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// 
        /// Executes the middleware action.
        /// 
        /// The current HTTP context.
        /// The network manager.
        /// The server configuration manager.
        /// The async task.
        public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
        {
            if (httpContext.IsLocal())
            {
                await _next(httpContext).ConfigureAwait(false);
                return;
            }
            var remoteIp = httpContext.GetNormalizedRemoteIp();
            if (serverConfigurationManager.Configuration.EnableRemoteAccess)
            {
                var addressFilter = serverConfigurationManager.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
                if (addressFilter.Length > 0 && !networkManager.IsInLocalNetwork(remoteIp))
                {
                    if (serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist)
                    {
                        if (networkManager.IsAddressInSubnets(remoteIp, addressFilter))
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (!networkManager.IsAddressInSubnets(remoteIp, addressFilter))
                        {
                            return;
                        }
                    }
                }
            }
            else
            {
                if (!networkManager.IsInLocalNetwork(remoteIp))
                {
                    return;
                }
            }
            await _next(httpContext).ConfigureAwait(false);
        }
    }
}