//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;

namespace CommunityServer.Components.HttpHandler
{
	/// <summary>
	/// Many aggregators display images.  AggBugHandler enables us to track when a post is read from a syndication file by appened the postid
	/// to the image. We then return an invisible 1x1 image to the client.
	/// </summary>
	public class AggBugHandler : IHttpHandler
	{
		public AggBugHandler()
		{
		}

        private static byte[] _bytes = Convert.FromBase64String("R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
        #region IHttpHandler Members

        /// <summary>
        /// Adds the to the AggCount and renders the image. This value (image) should be cached locally for 12 hours
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
           int postID = CSContext.Current.PostID;
            if(postID > 0)
            {
                Views.AddAggCount(postID);
            }

            if(!_CachedVersionIsOkay(context.Request))
            {
                context.Response.ContentType = "image/gif";
                context.Response.AppendHeader("Content-Length",_bytes.Length.ToString());
                context.Response.Cache.SetLastModified(DateTime.Now);
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.BinaryWrite(_bytes);
                context.Response.End();
            }
            else
            {
                context.Response.StatusCode = 304;
                context.Response.SuppressContent = true;
                return; 
            }


        }

        private bool _CachedVersionIsOkay(HttpRequest Request)
        {
            string ifModified = Request.Headers["If-Modified-Since"];

            if (ifModified != null)
            {
				// Some clients appear to be sending unrecognizable DateTime formats in the
				//	If-Modified-Since header. Added a Try/Catch to prevent logging these errors for CS 2.1.
				try 
				{
	                DateTime lastModified = DateTime.Parse(ifModified);
		            return DateTime.Now.AddHours(-12) < lastModified;
                }
                catch {}
            }

            return false;
        }

        public bool IsReusable
        {
            get
            {
                // TODO:  Add AggBugHandler.IsReusable getter implementation
                return false;
            }
        }

        #endregion
    }
}
