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

using System;
using System.Web;
using System.Text.RegularExpressions;

namespace CommunityServer.Components {
    /// <summary>
    /// Summary description for UserCookie.
    /// </summary>
    public class UserCookie {

        #region Member variables and constructor

		protected HttpCookie userCookie;
        string cookieName;//= "CommunityServer-UserCookie";
        CSContext csContext = CSContext.Current;
        HttpContext context = null;
        User user;
        string cookieKey;

        public UserCookie( User user ) {
            this.user = user;

            //Allows different users on the same machine to hide unique sets of forums
            cookieName = "CommunityServer-UserCookie" + user.UserID.ToString();
            context = csContext.Context;
            userCookie = context.Request.Cookies[cookieName];
            
            //use a global key
            cookieKey = string.Format("hfg-{0}",CSContext.Current.ApplicationType);
            

            // Did we find a cookie?
            //
            if (userCookie == null) {
                userCookie = new HttpCookie(cookieName);
            } else {
                userCookie = context.Request.Cookies[cookieName];
            }

        }


		#endregion

        #region Helper functions

		protected void WriteCookie() 
		{
			WriteCookie(this.userCookie, 365, true);
		}

		public void WriteCookie(HttpCookie cookie, int days, bool autoLogin)
		{
			string cookieDomain = csContext.SiteSettings.CookieDomain.ToString();
			string currentURL = HttpContext.Current.Request.Url.AbsoluteUri;
			Regex matchNotTLD = new Regex("[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)+$",RegexOptions.Compiled|RegexOptions.IgnoreCase);

			//Check if we are not breaking functionality because of bad domain setting
			if( (matchNotTLD.IsMatch(cookieDomain)) && (currentURL.IndexOf(cookieDomain) > -1) )
			{
				cookie.Path="/";
				cookie.Domain=cookieDomain;
			}

			if (autoLogin)
				cookie.Expires = DateTime.Now.AddDays(days);

			context.Response.Cookies.Add(cookie);
		}		

		public void DeleteCookie(HttpCookie cookie)
		{
			string cookieDomain = csContext.SiteSettings.CookieDomain.ToString();
			string currentURL = HttpContext.Current.Request.Url.AbsoluteUri;
			Regex matchNotTLD = new Regex("[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)+$",RegexOptions.Compiled|RegexOptions.IgnoreCase);

			//Check if we are not breaking functionality because of bad domain setting
			if( (matchNotTLD.IsMatch(cookieDomain)) && (currentURL.IndexOf(cookieDomain) > -1) )
			{
				cookie.Path="/";
				cookie.Domain=cookieDomain;
			}
			
			cookie.Expires = new System.DateTime(1999, 10, 12);
			context.Response.Cookies.Add(cookie);
		}

        #endregion

        #region Last Visit
		/// <summary>
		/// This method should only be called at the beginning of each session.
		/// It will update the LastVisit(lv) by looking at the MostRecentActivity(mra)
		/// NOTE: If MostRecentActivity doesn't exist, it's the user's first time to the site
		/// </summary>
		public void UpdateLastVisit()
		{
			if (userCookie["mra"] == null)
				userCookie["lv"] = DateTime.Parse("1/1/1999").ToString();
			else
				userCookie["lv"] = userCookie["mra"];

			WriteCookie();
		}

		public void UpdateMostRecentActivity()
		{
			userCookie["mra"] = DateTime.Now.ToString();
			WriteCookie();
		}

		public DateTime LastVisit
		{
			get
			{
				if (userCookie["lv"] == null)
					UpdateLastVisit();

				return DateTime.Parse(userCookie["lv"]);
			}
		}
		#endregion

        #region Forum Filter/View Settings
        public void SaveForumOptions (int forumID, string settings) {
            userCookie["fo" + forumID] = settings;

            // Write the updated cookie
            WriteCookie();
        }

        public ForumUserOptions GetForumOptions (int forumID) {
            return new ForumUserOptions(userCookie["fo" + forumID]);
        }
        #endregion

        #region Hidden forum groups
        public string[] HiddenGroups {

            get {
                // Do we have values?
                //
                
                if (userCookie.Values[cookieKey] != null)
                    return userCookie.Values[cookieKey].Split(',');

                return new string[0];
            }
        }

        public void RemoveHiddenForumGroup(int forumGroupID) {

            string hfg = "," + userCookie.Values[cookieKey] + ",";

            // Add some details to the string to do a simple replace
            //
            hfg = hfg.Replace("," + forumGroupID + ",", ",");

            // Trim the string
            //
            hfg = hfg.TrimStart(',').TrimEnd(',');

            userCookie.Values[cookieKey] = hfg;

            WriteCookie();
        }

        public void AddHiddenForumGroup(int forumGroupID) {
            string[] s = HiddenGroups;
            string hfg = string.Empty;

            // Do we already have this forum group
            //
            for (int i = 0; i < s.Length; i++)
                if (s[i] == forumGroupID.ToString())
                    return;

            string[] s1 = new String[s.Length + 1];
            s.CopyTo(s1, 0);
            s1[s1.Length - 1] = forumGroupID.ToString();
                
            for (int i=0; i<s1.Length; i++)
                hfg = hfg + s1[i] + ",";

            // Trim off the extra comma
            //
            hfg = hfg.TrimStart(',').TrimEnd(',');

            userCookie.Values[cookieKey] = hfg;

            WriteCookie();
        }
        #endregion

    }

}
