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

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;

namespace CommunityServer.Files.Controls
{
	public class UploadAttachment : CommunityServer.Controls.UploadAttachment
	{
		CSContext csContext = CSContext.Current;

		private Section _section;
		protected override Section Section
		{
			get
			{
				if (_section == null)
					_section = Folders.GetFolder(csContext.SectionID);

				return _section;
			}
		}

		protected override bool IsFileValid(string filename, bool isRemote, int fileSizeBytes, ref string message)
		{
			FileGalleryAttachmentSettings fgas = FileGalleryConfiguration.GetConfig().AttachmentSettings;
			if (fgas.ValidateExtensions && !csContext.User.IsFileAdministrator)
			{
				if (!fgas.ValidationRegex.IsMatch(filename))
				{
					message = string.Format(ResourceManager.GetString("UploadAttachment_InvalidFileExtension"), fgas.Extensions.Replace(";", ","));
					return false;
				}
			}
		
			if (!((Folder) Section).IsFilenameValid(filename))
			{
				string allowedExtensions = ((Folder) Section).AllowedFileExtensions.Replace(";", ",");
				string restrictedExtensions = ((Folder) Section).RestrictedFileExtensions.Replace(";", ",");
				
				if (Globals.IsNullorEmpty(restrictedExtensions) || Globals.IsNullorEmpty(allowedExtensions))
				{
					if (Globals.IsNullorEmpty(restrictedExtensions))
						message = string.Format(ResourceManager.GetString("UploadAttachment_InvalidFileExtension"), allowedExtensions);
					else
						message = string.Format(ResourceManager.GetString("UploadAttachment_InvalidFileExtension_Deny"), restrictedExtensions);
				}
				else
					message = string.Format(ResourceManager.GetString("UploadAttachment_InvalidFileExtension_AllowAndDeny"), allowedExtensions, restrictedExtensions);

				return false;
			}

			return true;
		}
	}
}
