using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace RedirectVisitorsByCountryASPDotNetMVC.Filters
{
    public class RedirectVisitorsFilter : ActionFilterAttribute
    {
        private readonly string[] RedirectCountries = { "US", "GB" };
        private readonly string LicenseKey = "demo"; //replace this with your own IP2Location.io API key
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var pat = "\"country_code\":\"([A-Z]{2})\"";
            Regex r = new Regex(pat, RegexOptions.IgnoreCase);
            var data = CallWebService(filterContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"]);
            var countrycode = "";
            Match m = r.Match(data);

            if (m.Success)
            {
                countrycode = m.Groups[1].ToString();
            }

            if (RedirectCountries.Contains(countrycode))
            {
                filterContext.Result = new RedirectResult("https://www.ip2location.com/");
            }
            base.OnActionExecuting(filterContext);
        }

        private string CallWebService(string ip)
        {
            var httpClient = new HttpClient();
            Task<string> data = httpClient.GetStringAsync("https://api.ip2location.io/?key=" + LicenseKey + "&ip=" + ip);
            return data.Result;

        }
    }
}