using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Caching;

namespace WebMobile.Extend
{
    public class SafeAddress
    {
        static object _thisLock = new object();

        public SafeAddress()
        {
        }

        public bool IsSafe(HttpContext context, string userEmail)
        {
            const string cacheKey1 = "SafeAddress4Download";
            IpAddressFilter safeAddr = (IpAddressFilter)context.Cache[cacheKey1];
            if (safeAddr == null)
            {
                lock (_thisLock)
                {
                    safeAddr = (IpAddressFilter)context.Cache[cacheKey1];
                    if (safeAddr == null)
                    {
                        string appDataPath = context.Server.MapPath("~/app_data");
                        string cfgFile = string.Format("{0}\\SafeAddress4Download.txt", appDataPath);
                        safeAddr = new IpAddressFilter(cfgFile);
                        context.Cache.Insert(cacheKey1, safeAddr, new CacheDependency(cfgFile));
                    }
                }
            }
            if (safeAddr.Filtered(context.Request.UserHostAddress))
                return true;

            const string cacheKey2 = "SafeAccount4Download";
            SafeAccountFilter safeAccount = (SafeAccountFilter)context.Cache[cacheKey2];
            if (safeAccount == null)
            {
                lock (_thisLock)
                {
                    safeAccount = (SafeAccountFilter)context.Cache[cacheKey2];
                    if (safeAccount == null)
                    {
                        string appDataPath = context.Server.MapPath("~/app_data");
                        string cfgFile = string.Format("{0}\\SafeAccount4Download.txt", appDataPath);
                        safeAccount = new SafeAccountFilter(cfgFile);
                        context.Cache.Insert(cacheKey2, safeAccount, new CacheDependency(cfgFile));
                    }
                }
            }
            return safeAccount.Filtered(userEmail);
        }        
    }
}