
using System;
using System.Text;
using System.Web;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;

//namespace Legalsoft.Workflow.Engine
//{
    public class myModuler : IHttpModule
    {
        void IHttpModule.Dispose() { }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PostReleaseRequestState += new EventHandler(context_EndRequest);
        }

        public void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            string scr = "";
            if (app.Request["SCRIPT_NAME"] != null) scr = app.Request["SCRIPT_NAME"].ToString().ToLower();
            if (scr.Contains("?")) scr = scr.Substring(0, scr.IndexOf("?"));

            if (scr.StartsWith("/api/v1/flow/progress/"))
            {
                string path = "/api/v1/flow/progress.aspx";
                string qry = "id=";
                string[] sa = scr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                qry += sa[sa.Length - 1].Replace(".aspx", "");
                app.Context.RewritePath(path, String.Empty, qry);
                return;
            }

            if (scr.StartsWith("/api/v1/flow/timeline/"))
            {
                string path = "/api/v1/flow/timeline.aspx";
                string qry = "id=";
                string[] sa = scr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                qry += sa[sa.Length - 1].Replace(".aspx", "");
                app.Context.RewritePath(path, String.Empty, qry);
                return;
            }
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            if (app.Request["HTTP_X_MICROSOFTAJAX"] != null || app.Request["Anthem_CallBack"] != null) return;
            if (app.Response.ContentType != "text/html") return;

            string encodings = app.Request.Headers.Get("Accept-Encoding");
            if (encodings == null) return;
            encodings = encodings.ToLower();

            Stream s = app.Response.Filter;
            if (encodings.Contains("gzip"))
            {
                app.Response.Filter = new GZipStream(s, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");
                return;
            }
            if (encodings.Contains("deflate"))
            {
                app.Response.Filter = new DeflateStream(s, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
                return;
            }
        }
    }
//}

