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

using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;

using System.ComponentModel;
using System.Web.Security;

namespace CommunityServer.Controls {

    // *********************************************************************
    //  Logout
    //
    /// <summary>
    /// This server control renders and handles the login UI for the user.
    /// </summary>
    // ***********************************************************************/
    [
    ParseChildren(true)
    ]
    public class Logout : TemplatedWebControl {

        // *********************************************************************
        //  Logout
        //
        /// <summary>
        /// Constructor
        /// </summary>
        // ***********************************************************************/
        public Logout() : base() {}

        
		protected override void AttachChildControls()
		{
			IText label;
			CSContext cntx = CSContext.Current;
			if(Context.Request.IsAuthenticated)
			{
				// log the user out
				FormsAuthentication.SignOut();
				
				HttpCookie formsAuthCookie;
				formsAuthCookie = FormsAuthentication.GetAuthCookie(cntx.UserName, true);

                formsAuthCookie = AlterAuthCookie(formsAuthCookie);
			    
				UserCookie userCookie = cntx.User.GetUserCookie();
				userCookie.DeleteCookie(formsAuthCookie);

				// Nuke the roles cookie
                CommunityServer.Components.Roles.SignOut();

				// If using passport, we need to send them to Passport's logout page
				// We cannot rely on checking the authenticationType or anything because MemberRoles overwrites it in one of its HttpModules
				if(Context.Items.Contains("PassportUID"))
					Context.Response.Redirect( (new PassportIdentity()).LogoutURL(), true );
				else
				// Redirect them back to the logout page so that the header will reflect a logged out state
				Context.Response.Redirect( Globals.GetSiteUrls().Logout, true );
			}

			label = FindText("LogoutText");
			if(label != null)
				label.Text = string.Format(ResourceManager.GetString("Logout_Status"), cntx.SiteSettings.SiteName);
        }

        /// <summary>
        /// This method can be overridden to alter settings in the auth cookie such as the Domain
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        protected virtual HttpCookie AlterAuthCookie(HttpCookie cookie)
        {
            return cookie;
        }


    }
}
