using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using TABS.MailCarrier.AuxLib;

/// <summary>
/// Summary description for SafeAddress
/// </summary>
public class IpAddressFilter
{
    private IpFilter2 _ipFilter = new IpFilter2("");

    public IpAddressFilter(string cfgFile)
    {
        try
        {
            string ip4base_p = @"(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])";
            string ip4_p = string.Format("^{0}$", ip4base_p);
            string ip4mask_p = string.Format("^(?<ip>{0})/(?<mask>{0})$", ip4base_p);
            string ip4range_p = string.Format("^(?<begin>{0})~(?<end>{0})$", ip4base_p);
            Regex rIp4 = new Regex(ip4_p, RegexOptions.IgnoreCase);
            Regex rIp4Mask = new Regex(ip4mask_p, RegexOptions.IgnoreCase);
            Regex rIp4Range = new Regex(ip4range_p, RegexOptions.IgnoreCase);

            using (StreamReader sr = new StreamReader(cfgFile))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    int p = line.IndexOf('#');
                    if (p != -1) line = line.Substring(0, p);
                    line = line.Trim();

                    Match m = rIp4Mask.Match(line);
                    if (m.Success)
                    {
                        _ipFilter.AddIp(m.Groups["ip"].ToString(), m.Groups["mask"].ToString());
                    }
                    else
                    {
                        m = rIp4Range.Match(line);
                        if (m.Success)
                        {
                            _ipFilter.AddIpRange(m.Groups["begin"].ToString(), m.Groups["end"].ToString());
                        }
                        else
                        {
                            m = rIp4.Match(line);
                            if (m.Success)
                            {
                                _ipFilter.AddIp(m.Value);
                            }
                        }
                    }
                }
            }
        }
        catch { }
    }

    public bool Filtered(string ip)
    {
        if (ip == "::1") ip = "127.0.0.1";
        return !_ipFilter.Pass(ip);
    }
}