using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;

namespace Fivestops.Oxide
{
    class OxideApplicationPool
    {
        private Hashtable m_htApplications = new Hashtable();
        private ClientSponsor m_csSponsor = new ClientSponsor();

        public void ProcessRequests()
        {
            while (true)
            {
                try
                {
                    this.ProcessRequest (CausalityClient.GetRequest());
                }
                catch (Exception e)
                {
                    Console.WriteLine ("ex: {0}", e);
                }
            }
        }

        private void ProcessRequest (IntPtr request)
        {
            OxideApplicationHost oahHost = this.GetHost (
                    CausalityClient.GetTransactionVariable (request, "docroot"));

            oahHost.HandleRequest (request);
        }

        private OxideApplicationHost GetHost (string docroot)
        {
            OxideApplicationHost oahHost = (OxideApplicationHost) 
                m_htApplications[docroot];

            if (oahHost == null)
            {
                oahHost = OxideApplicationHost.CreateApplicationHost (
                        "/", docroot);

                m_csSponsor.Register (oahHost);

                m_htApplications[docroot] = oahHost;
            }

            return (oahHost);
        }
    }
}
