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

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CA = ComponentArt.Web.UI;

namespace CommunityServer.Controls {

    public class UserProfile : TemplatedWebControl {
        User user;
        CSContext csContext = CSContext.Current;

        // *********************************************************************
        //  UserProfile
        //
        /// <summary>
        /// Constructor
        /// </summary>
        /// 
        // ********************************************************************/
        public UserProfile()
		{
			// Force login if settings don't allow anonymous viewing of profiles
			if ((csContext.User.IsAnonymous) && (csContext.SiteSettings.RequireAuthenticationForProfiles))
				Context.Response.Redirect(Globals.GetSiteUrls().Login);

			int userid = csContext.UserID;
            
			// Do we have a valid UserID?
			//
			if(userid <= 0) {

				// Is there a username?
				if (Context.Request.QueryString["UserName"] == string.Empty)
					throw new CSException(CSExceptionType.UserNotFound);
				else
					user = Users.GetUser(0, Context.Request.QueryString["UserName"], false, true);
			} else {
				user = Users.GetUser(csContext.UserID, false, true);
			}

            if(user.IsAnonymous)
            {
                Context.Response.Redirect(Globals.GetSiteUrls().Home);
                Context.Response.End();

            }

            Users.ValidateUserAccess(user,csContext.User);
            
        }
	
        // *********************************************************************
        //  Initializeskin
        //
        /// <summary>
        /// This method populates the user control used to edit a user's information
        /// </summary>
        /// 
        // ***********************************************************************/

        protected override void AttachChildControls()
        {
			Control privateContactInformation = FindControl("PrivateContactInformation");
			User u;

			if (privateContactInformation != null)
				privateContactInformation.Visible = !csContext.User.IsAnonymous;

            CA.CallBack SearchCallBack = FindControl("SearchCallBack") as CA.CallBack;

			if (SearchCallBack != null)
				SearchCallBack.Callback +=new CA.CallBack.CallbackEventHandler(SearchCallBack_Callback);

//            Image spinner = FindControl("spinner") as Image;
//            spinner.ImageUrl =  CommunityServer.Components.Globals.GetSiteUrls().LoadingImageUrl;

            // Find controls for About section
            //
			if (user.Profile.CommonName != string.Empty)
				(FindText("Username")).Text = user.Profile.CommonName;
			else
				(FindText("Username")).Text = user.Username;

            (FindText("TimeZone")).Text = user.Profile.Timezone.ToString();
            (FindText("Location")).Text = user.Profile.Location.ToString();
            (FindText("Occupation")).Text = user.Profile.Occupation.ToString();
            (FindText("Interests")).Text = user.Profile.Interests.ToString();

            // Format the output
            //
            if (!csContext.User.IsAnonymous) {
                u = csContext.User;

                (FindText("JoinedDate")).Text = user.DateCreated.ToString( u.Profile.DateFormat );
                (FindText("LastActivityDate")).Text = user.LastActivity.ToString( u.Profile.DateFormat );
            } else {
                (FindText("JoinedDate")).Text = user.DateCreated.ToString();
                (FindText("LastActivityDate")).Text = user.LastActivity.ToString();
            }

            
			// Format the birthday
			//
			if(user.Profile.BirthDate > DateTime.MinValue)
			{
				if (!csContext.User.IsAnonymous) 
				{
					u = csContext.User;

					(FindText("Birthday")).Text = user.Profile.BirthDate.Date.ToString( u.Profile.DateFormat );
				} 
				else 
				{
					(FindText("Birthday")).Text = String.Format("{0:d}", user.Profile.BirthDate);
				}
				(FindText("Age")).Text = String.Format(ResourceManager.GetString("ViewUserProfile_Age"),Users.GetUserAge(user).ToString());
			}

            
            // Does the user have a web url?
            //
            if (user.Profile.WebAddress.Length > 0) {
                HyperLink url = (HyperLink) FindControl("WebURL");
                url.NavigateUrl = user.Profile.WebAddress;
                url.Text = user.Profile.WebAddress;
            }

            // Does the user have a blog url?
            //
            if (user.Profile.WebLog.Length > 0) {
                HyperLink url = (HyperLink) FindControl("BlogURL");
                url.NavigateUrl = user.Profile.WebLog;
                url.Text = user.Profile.WebLog;
            }

			// Does the user have a gallery url?
			//
			if (user.Profile.WebGallery.Length > 0) 
			{
				HyperLink url = (HyperLink) FindControl("GalleryURL");
				url.NavigateUrl = user.Profile.WebGallery;
				url.Text = user.Profile.WebGallery;
			}

            // Does the user have a public email?
			Control c = FindControl("Email");
            if (user.Profile.PublicEmail.Length > 0) 
			{
				if (c != null)
				{
					if (c is HyperLink)
					{
						HyperLink url = c as HyperLink;
						url.NavigateUrl = "mailto:" + user.Profile.PublicEmail;
						url.Text = ResourceManager.GetString("ViewUserProfile_Email");
					}
					else if (c is ModalLink)
					{
						ModalLink url = c as ModalLink;
						url.Url = SiteUrls.Instance().EmailToUser(user.UserID);
						url.Text = ResourceManager.GetString("ViewUserProfile_Email");
					}
				}
            }
			else if (c != null)
				c.Visible = false;

			// Does the user have private messages enabled?
			Control pm = FindControl("PrivateMessage");
			//if (user.EnablePrivateMessages) { -- there is nowhere to set EnablePrivateMessages... so ignoring for now
				if (pm != null)
				{
					if (pm is HyperLink)
					{
						HyperLink url = pm as HyperLink;
						url.NavigateUrl = SiteUrls.Instance().PrivateMessage(user.UserID);
						url.Text = ResourceManager.GetString("ForumMembers_PrivateMessages");
					}
					else if (pm is ModalLink)
					{
						ModalLink url = pm as ModalLink;
						url.Url = SiteUrls.Instance().PrivateMessage(user.UserID);
						url.Text = ResourceManager.GetString("ForumMembers_PrivateMessages");
					}
				}
			//}

  
             // Find controls for Avatar/Post section
            //
            if ( (user.HasAvatar) && (user.EnableAvatar) && (user.IsAvatarApproved) ) {
                UserAvatar avatar = (UserAvatar) FindControl("Avatar");

				if (avatar != null)
				{
					avatar.User = user;
					avatar.Visible = true;
				}
            }

			(FindText("Signature")).Text = user.Profile.SignatureFormatted;


            // Find controls in Contact section
            //
            (FindText("MSNIM")).Text = user.Profile.MsnIM;
            (FindText("AOLIM")).Text = user.Profile.AolIM;
            (FindText("YahooIM")).Text = user.Profile.YahooIM;
            (FindText("ICQ")).Text = user.Profile.IcqIM;


            // Post statistics rank, etc.
            //
            (FindText("TotalPosts")).Text = user.TotalPosts.ToString("n0");
			(FindText("Rank")).Text = ((int)user.PostRank[0]).ToString();

			if (CanSeeUserPoints())
			{
				FindControl("PointsRow").Visible = true;
				(FindText("Points")).Text = user.Points.ToString("n0");
			}

            IText aboutBio = FindText("AboutBio");
            if(aboutBio != null)
                aboutBio.Text = string.Format(ResourceManager.GetString("ViewUserProfile_AboutBioFormat"), user.CommonNameOrUserName);

            IText bio = FindText("Bio");
            if(bio != null)
            {
                if(!Globals.IsNullorEmpty(user.Profile.Bio))
                    bio.Text = user.Profile.Bio;
                else
                    bio.Text = ResourceManager.GetString("ViewUserProfile_BioMissing");
            }

            // Display recent posts

			// Shared Favorites
			Repeater FavoriteUsers = (Repeater)FindControl("FavoriteUsers");
			if (FavoriteUsers != null)
			{
				if ((user.FavoritesShared & FavoriteType.User) == FavoriteType.User)
					FavoriteUsers.DataSource = Favorites.GetUsers(user.UserID);

				FavoriteUsers.DataBind();
			}

			Repeater FavoritePosts = (Repeater)FindControl("FavoritePosts");
			if (FavoritePosts != null)
			{
				if ((user.FavoritesShared & FavoriteType.Post) == FavoriteType.Post)
					FavoritePosts.DataSource = Favorites.GetPosts(user.UserID);

				FavoritePosts.DataBind();
			}

			Repeater FavoriteSections = (Repeater)FindControl("FavoriteSections");
			if (FavoriteSections != null)
			{
				if ((user.FavoritesShared & FavoriteType.Section) == FavoriteType.Section)
					FavoriteSections.DataSource = Favorites.GetSections(user.UserID);

				FavoriteSections.DataBind();
			}

            Control PMArea = FindControl("PMArea");
            if(PMArea != null)
            {
                PMArea.Visible = Users.EnablePM(user);
            }

            UsersOnline.SetLocation("Viewing " + user.DisplayName + "'s profile");
        }

        private void SearchCallBack_Callback(object sender, CA.CallBackEventArgs e)
        {

            

            Repeater searchRepeater = FindControl("SearchRepeater") as Repeater;
            searchRepeater.ItemDataBound +=new RepeaterItemEventHandler(searchRepeater_ItemDataBound);
            SearchQuery query = new SearchQuery();
            query.PageIndex = 0;
            query.PageSize = 10;
            query.UsersToSearch = new int[1] {user.UserID};
            query.SortBy = SearchSort.DateDescending;
                    
            SearchResultSet searchResult = CSSearch.Search(query);
            searchRepeater.DataSource = searchResult.Posts;
            searchRepeater.DataBind();
            searchRepeater.RenderControl(e.Output);
        }

		private bool CanSeeUserPoints()
		{
			if (!csContext.SiteSettings.EnablePointSystem)
				return false;

			switch (csContext.SiteSettings.PointsUserDisplayLevel)
			{
				case DisplayLevel.None:
					return false;
				case DisplayLevel.Everyone:
					return true;
				case DisplayLevel.AdministratorsAndModerators:
					return (csContext.User.IsAdministrator || csContext.User.IsModerator);
				default:
					return false;
			}
        }

        private void searchRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            IndexPost post = e.Item.DataItem as IndexPost;
            if (post == null)
                return;
            
            switch (e.Item.ItemType) 
            {
                case  ListItemType.Item:
                case  ListItemType.AlternatingItem:
				
                    HyperLink SectionUrl = e.Item.FindControl("SectionUrl") as HyperLink;
                    if(SectionUrl != null && Globals.IsNullorEmpty(SectionUrl.NavigateUrl))
                    {
                        CSApplicationData data = ApplicationSet.Data(post.ApplicationType);
                        if(data != null)
                        {
                            SectionUrl.NavigateUrl = data.SectionUrl(post);
                        }
                        else
                        {
                            SectionUrl.Visible = false;
                        }
                    }

                    break;
            }
        }
    }
}
