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

using System.IO;
using System;
using System.Security;
using System.Collections;
using System.Xml;
using CommunityServer.Components;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// CSModule to auto create a user gallery when a user registers
	/// </summary>
	public class AutoGalleryCreate : ICSModule
	{
		public AutoGalleryCreate() { }

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PostUserUpdate += new CSUserEventHandler(csa_PostUserUpdate);
		}

		private void csa_PostUserUpdate(User user, CSEventArgs e)
		{
			if(user != null && e.State == ObjectState.Create)
			{
				GalleryConfiguration config = GalleryConfiguration.Instance();
				if(config.AutoCreateGallery)
				{
					string formattedKey = null;
					CSContext cSContext = CSContext.Current;
					Globals.ValidateApplicationKey(user.Username, out formattedKey);

					if(Globals.IsNullorEmpty(formattedKey) || Galleries.Exists(formattedKey))
					{
						return;
					}

					Gallery g = new Gallery();
					g.ApplicationKey = formattedKey;

                    int groupid = config.DefaultGroupID;
                    if (groupid <= 0)
                    {
                        ArrayList groups = GalleryGroups.GetGroups(true, false, false);
                        if (groups.Count > 0)
                            groupid = ((Group)groups[0]).GroupID;
                    }

					if(groupid <=0)
						return;

                    g.GroupID = groupid;
                    g.Name = user.Username;
					g.IsActive = true;
					g.SettingsID = cSContext.SiteSettings.SettingsID;
					g.ApplicationType = ApplicationType.Gallery;
					g.DateCreated = DateTime.Now;
					g.Owners = user.Username;
					g.IsSearchable = true;
					g.EnableRss = true;

					//Create The Gallery
					g.SectionID = CommunityServer.Galleries.Galleries.AddGallery(g);

					//Create the Folder on the webserver
					try
					{
						if(GalleryConfiguration.Instance().CreateGalleryDirectories)
							WebDirectory.Create(Globals.GetSiteUrls().Locations["galleries"] + g.ApplicationKey);
					}
					catch(IOException ex)
					{ new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
					catch(SecurityException ex)
					{ new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
					catch { }
			
					//Not Cluster safe, but lets try and update the cache
					CommunityServer.Galleries.Galleries.GetGalleries(cSContext.User.UserID, true, true, true);
				}
			}
		}
	}
}
