using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.Caching;
using System.Web.UI.WebControls;
using System.Xml;

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

        private class Store
        {
            public Dictionary<Guid, int> boards = new Dictionary<Guid, int>();
            public Dictionary<string, int> admins = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        }

        public DisplayBoardFilter()
        {
        }

        public bool Pass(HttpContext context, Guid boardId, string userEmail)
        {
            Store store = GetStore(context);
            return store.boards.ContainsKey(boardId) || store.admins.ContainsKey(userEmail);
        }

        public bool PassAdmin(HttpContext context, string userEmail)
        {
            Store store = GetStore(context);
            return store.admins.ContainsKey(userEmail);
        }

        private static Store GetStore(HttpContext context)
        {
            const string cacheKey = "DisplayBoardFilterStore";
            Store store = (Store)context.Cache[cacheKey];
            if (store == null)
            {
                lock (_thisLock)
                {
                    store = (Store)context.Cache[cacheKey];
                    if (store == null)
                    {
                        string appDataPath = context.Server.MapPath("~/app_data");
                        string xmlFile = string.Format("{0}\\DisplayBoardFilter.xml", appDataPath);

                        store = new Store();
                        XmlDocument doc = new XmlDocument();
                        doc.Load(xmlFile);

                        XmlElement root = doc.DocumentElement;
                        foreach (XmlNode node in root.SelectNodes("/displayboard/permit/board"))
                        {
                            Guid bid = new Guid(node["id"].InnerText);
                            if (!store.boards.ContainsKey(bid))
                                store.boards.Add(bid, 0);
                        }

                        foreach (XmlNode node in root.SelectNodes("/displayboard/adminlist/admin"))
                        {
                            string admin = node.InnerText;
                            if (!store.admins.ContainsKey(admin))
                                store.admins.Add(admin, 0);
                        }

                        context.Cache.Insert(cacheKey, store, new CacheDependency(xmlFile));
                    }
                }
            }

            return store;
        }
    }
}