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

using System.IO;
using System.Web;
using CommunityServer.Components;
using CommunityServer.Configuration;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Summary description for GalleryAttachmentSettings.
	/// </summary>
	[System.Xml.Serialization.XmlRoot("AttachmentSettings")]
	public class GalleryAttachmentSettings : AttachmentSettings
	{

		
		public GalleryAttachmentSettings()
		{
			this.EnableDataStoreStorage = true;
			this.EnableDirectLinks = false;
			this.EnableFileSystemStorage = true;
			this.Extensions = "all";
			this.FileSystemStorageLocation = "~/photos/storage";
		}


		#region File Name
		
		public string GetLocalFileName(GalleryPost post)
		{
			return string.Format( "{0}{1}", CalculateFileSystemStorageLocation(), GetFileName(post));
		}

		public string GetFileName(GalleryPost post)
		{
			return string.Format( "{0}.{1}.{2}.{3}", post.Section.SettingsID, post.SectionID, post.PostID, Encode(post.Attachment.FileName)) ;
		}

		protected override string GetFileName()
		{
			return GetLocalFileName(GalleryPosts.GetPicture(CSContext.Current.PostID));
		}
		
		#endregion

		protected override PostAttachment GetFile()
		{
			string name = GetFileName();
			if (!File.Exists(name))
			{
				GalleryPost post = GalleryPosts.GetPicture(CSContext.Current.PostID);
				PostAttachmentMetaData pictureData = PostAttachments.GetPostAttachtmentMetaData(post.PostID);
				string file = GetLocalFileName(post);

				//If the file exists on the disk, load it from there
				if (!File.Exists(file))
				{
					//check the old location on the file system
					string oldfile = file.Replace("." + Encode(pictureData.FileName), "");
					if (File.Exists(oldfile))
					{
						//move it to the new location
						File.Move(oldfile, file);
					}
				}
			}
			
			return base.GetFile();
		}


		/// <summary>
		/// Clears the storage for CS2.0 and below file patterns
		/// </summary>
		/// <param name="SectionID"></param>
		public void LegacyClearStorage(int SectionID)
		{
			// Delete all of the files for this section
			FileInfo[] files = (new DirectoryInfo(CalculateFileSystemStorageLocation())).GetFiles(CSContext.Current.SiteSettings.SettingsID + "." + SectionID + ".*");
			foreach(FileInfo file in files)
			{
					file.Delete();
			}
		}

		public override void DeleteAttachmentFromDisk(int postID)
		{
			GalleryPost p = GalleryPosts.GetPicture(postID);
			this.DeleteAttachmentFromDisk(p) ;
		}

	}
}
