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

using System;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Configuration;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;
using FormLabel = CommunityServer.ControlPanel.Controls.FormLabel;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Galleries
{
	/// <summary>
	/// Summary description for AttachmentPage.
	/// </summary>
	public class AttachmentPage : BaseGalleryPage
	{

		#region Child Controls

        protected CommunityServer.Controls.Style ControlPanelStyle;
        protected HtmlInputFile AttachmentData;
        protected LinkButton DescButton;
        protected TextBox  FriendlyName;
        protected TextBox FileName;
        protected HtmlInputHidden uploadType;
        protected RegularExpressionValidator FileNameValidator;
        protected RegularExpressionValidator AttachmentDataValidator;
        protected HtmlGenericControl uploadtypeQuestion, FriendlyNameTag, UploadTag, RemoteTag, ButtonTag;
        protected Script Script1;
        protected FormLabel Formlabel2;
        protected FormLabel FormLabel1;
		protected MPContent bcr;
		protected MPContainer MPContainer;
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol2;
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol1;
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol3;
        protected FormLabel Formlabel3;

		#endregion

		private void Page_Load(object sender, EventArgs e)
		{
			FileNameValidator.Text = AttachmentDataValidator.Text = ResourceManager.GetString("CP_Photos_Attachment_UploadAttachment_InvlalidFileType");
			DescButton.Text = ResourceManager.GetString("CP_Photos_Attachment_Upload");

			AttachmentSettings fs = GalleryConfiguration.Instance().AttachmentSettings;

			AttachmentDataValidator.ValidationExpression = fs.ValidationPattern;
			FileNameValidator.ValidationExpression = fs.ValidationPattern;

			if(!IsPostBack)
			{
                bool remote = Permissions.ValidatePermissions(this.CurrentGallery,Permission.RemoteAttachment,this.CurrentUser);
                bool local = Permissions.ValidatePermissions(this.CurrentGallery,Permission.LocalAttachment,this.CurrentUser);

                if(remote && local)
                {

                	HttpCookie cookie = Request.Cookies["UploadDetails"];
                    if(cookie != null)
                    {
                        FriendlyName.Text = cookie.Values["FriendlyName"];
                        FileName.Text = cookie.Values["FileName"];
                    }

                    if(Request.QueryString["Upload"] != null)
                    {
                        SetUI(true,false,false);
                    }
                    else if(Request.QueryString["Remote"] != null)
                    {
                        SetUI(false,true,false);
                    }
                    else
                    {
                        SetUI(false,false,true);
                    }

                }
                else if(remote)
                {
                     SetUI(false,true,false);
                }
                else
                {
                    SetUI(true,false,false);
                }

			}

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			this.DescButton.Click += new EventHandler(this.DescButton_Click);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		protected void SetUI(bool showUpload, bool showRemote, bool showQuestion)
		{
			UploadTag.Visible = showUpload;
			RemoteTag.Visible = showRemote;

			uploadtypeQuestion.Visible = showQuestion;
			FriendlyNameTag.Visible = !showQuestion;
			ButtonTag.Visible = !showQuestion;

			Head.AddTitle(ResourceManager.GetString("CP_Photos_PostEdit_FileToUpload_Detail"), this.Context);
		}


		private void DescButton_Click(object sender, EventArgs e)
        {
            if(Page.IsValid)
            {
                bool isServer =UploadTag.Visible;

                string name = null;
                
                if(!isServer)
                {
                    name = FileName.Text;
                }
                else
                {
                    name = AttachmentData.PostedFile.FileName;
                }

                if(Globals.IsNullorEmpty(name))
                    return;

                AttachmentSettings fs = GalleryConfiguration.Instance().AttachmentSettings;

                if(fs.ValidateExtensions && !CSContext.Current.User.IsGalleryAdministrator)
                {
                    if(!fs.ValidationRegex.IsMatch(name))
                        return;

                    
                }

                const string resultArray = "new Array(\"{0}\",\"{1}\",\"{2}\",{3})";

                PostAttachment pa = null;

                

                if(isServer)
                    pa = new PostAttachment(AttachmentData.PostedFile); 
                else
                {
                    try
                    {
                        pa = new PostAttachment(FileName.Text);
                    }
                    catch
                    {
                        pa = new PostAttachment();
                        pa.FileName = FileName.Text;
                        pa.ContentType = AttachmentSettings.GetMapping(FileName.Text);

                    }

                    pa.Content = null;
                }
                    

                pa.SectionID = this.CurrentGallery.SectionID;
                pa.DateCreated = DateTime.Now;
                pa.IsRemote = !isServer;

                if(!Globals.IsNullorEmpty(FriendlyName.Text))
                    pa.FriendlyFileName = FriendlyName.Text;

                
                    
            

                Guid g = Guid.NewGuid();

                CommonDataProvider.Instance().AddTemporaryPostAttachment(g,pa);
                
                string retVal = string.Format(resultArray,g, name.Replace("\"","@@@").Replace("\\","\\\\"),pa.FriendlyFileName.Replace("\"","@@@"),isServer.ToString().ToLower());

                HttpCookie cookie = new HttpCookie("UploadDetails");
                cookie.Values["FriendlyName"] = pa.FriendlyFileName;

                if(!isServer)
                    cookie.Values["FileName"] = FileName.Text;

                Response.Cookies.Add(cookie);

				Modal.ClosePage(Page, retVal) ;

            }
        }
	}
}
