using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using ServiceCommunication.SimpleService;
using ServiceCommunication.ComplexService;

namespace ServiceCommunication
{
    class ServiceHandlerFactory : IHttpHandlerFactory
    {
        #region IHttpHandlerFactory Members

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // sprawdza istnienie obiektu kontekstu
            if (context == null)
            {
                throw new ArgumentNullException("context", "Context can't be null");
            }

            // uzyskuje nazwę klasy z adresu URL "/xyz_InternalService.axd/methodname"
            string serviceName;
            string methodName;

            if (context.Request.RawUrl.Contains("_InternalService.axd") == false)
                throw new ArgumentException("Adres URL ma nieprawidłowy format");

            GetServiceAndMethodNameFromUrl(context.Request.RawUrl, out serviceName, out methodName);

            switch (serviceName.ToLower())
            {
                case "simplewcfservice":
                    return new WCFHandler(typeof(SimpleWCFService), methodName);
                case "complexwcfservice":
                    return new WCFHandler(typeof(ComplexWCFService), methodName);
                default:
                    throw new InvalidOperationException("Nieprawidłowa operacja usługi");
            }

        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }

        #endregion

        #region Private Methods

        void GetServiceAndMethodNameFromUrl(string rawUrl, out string serviceName, out string methodName)
        {
            int lastForwardSlash = rawUrl.LastIndexOf("/");
            int firstUnderScore = rawUrl.IndexOf("_");

            serviceName = rawUrl.Substring(1, firstUnderScore - 1);
            methodName = rawUrl.Substring(lastForwardSlash + 1);

        }

        #endregion
    }
}
