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

using System;
using System.Web;

namespace CommunityServer.Components {

	/// <summary>
	/// AutoLoginCookie handles read/write cookie operations to 
	/// save auto login preference on client's browser.
	/// </summary>
	public class AutoLoginCookie {
        
        #region Fields
        public string cookieName = "CommunityServer-AutoLoginCookie" ;
        HttpCookie theCookie = null;
        CSContext csContext = CSContext.Current;
        HttpContext context = null;
        #endregion

        #region Constructor
        public AutoLoginCookie () { 
            context = csContext.Context;
            theCookie = context.Request.Cookies[cookieName];
        
            // Init cookie object
            //
            if (theCookie == null)
                theCookie = new HttpCookie( cookieName );
            else 
                theCookie = context.Request.Cookies[cookieName];
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Writes auto login status on cookie.
        /// </summary>
        public bool Write (bool autoLogin) {
            if (theCookie == null)
                return false;
            
            // Save provided auto login status
            //
            theCookie.Value = autoLogin.ToString();                         

            // Make it a time dependent cookie: 1 year
            //
            theCookie.Expires = DateTime.Now.AddYears( 1 );

            // Add it to response stream
            //
            context.Response.Cookies.Add( theCookie );   

            return true;
        }

        /// <summary>
        /// Reads auto login status from cookie.
        /// </summary>
        public bool GetValue () {
            try {
                return Convert.ToBoolean( theCookie.Value.Trim() );
            }
            catch {
                return true;
            }
        }

        #endregion

        #region Properties
        /// <summary>
        /// Checks if cookie value is not null and non empty.
        /// </summary>
        public bool HasValue {
            get {
                return !Globals.IsNullorEmpty( theCookie.Value );
            }
        }
        #endregion
	}
}
