using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Generic;

namespace CefSharpWrap
{
    internal class ExternalRequestBlocker : DefaultRequestHandler
    {
        private readonly HashSet<string> _whiteList;
        private readonly Action<string> _nonWhiteListAccess;

        public ExternalRequestBlocker(Action<string> nonWhiteListAccess = null, params string[] whiteListScheme) : this(whiteListScheme)
        {
            _nonWhiteListAccess = nonWhiteListAccess;
        }

        public ExternalRequestBlocker(params string[] whiteListScheme)
        {
            _whiteList = new HashSet<string>(whiteListScheme) { "chrome-devtools", CefSharpWrapFactory.SchemeName };
        }

        public override bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
        {
            var uri = new Uri(request.Url);
            if (_whiteList.Contains(uri.Scheme)) return false;
            _nonWhiteListAccess?.Invoke(request.Url);
            return true;
        }
    }
}