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

using System;
using System.Web.UI.WebControls;
using CommunityServer.Reader.Components;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace CommunityServer.Reader.Controls
{
	/// <summary>
	/// Summary description for FolderListing.
	/// </summary>
	public class AddFeed : FeedReaderTemplatedWebControl
	{


		#region Private Members

		private TextBox txtFeedUrl;
		private Button btnAddFeed;
		private StatusMessage lStatus;

		#endregion

		#region Constructor(s)

		public AddFeed()
		{
			
		}

		#endregion

		#region Class Methods

		protected override void AttachChildControls()
		{
			txtFeedUrl = (TextBox) FindControl("txtFeedUrl");
			btnAddFeed = (Button) FindControl("btnAddFeed");
			lStatus = (StatusMessage) FindControl("lStatus");


			btnAddFeed.Click += new EventHandler(btnAddFeed_Click);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
				DataBind();

			// Let's handle passing in a URL via querystring as well.
			if (!Page.IsPostBack && Page.Request.QueryString["URL"] != null)
			{
				btnAddFeed_Click(this, new EventArgs());
			}
			
		
		}


		public override void DataBind()
		{
			base.DataBind ();

			CommunityServer.Controls.Head.AddTitle("Add Feed", this.Context);
		}

		#endregion

		#region Event Handlers


		private void btnAddFeed_Click(object sender, EventArgs e)
		{
			int userId = CSContext.Current.User.UserID;
			int folderId = 0;
			int parentFolderId = 0;
			string targetUrl = string.Empty;


			if (!Page.IsPostBack && Page.Request.QueryString["URL"] != null)
			{
				targetUrl = Page.Request.QueryString["URL"];
				txtFeedUrl.Text = targetUrl;
			}
			else
			{
				targetUrl = txtFeedUrl.Text;
			}

			if (Page.Request.QueryString["ID"] == null) return;


			string[] inputs = Page.Request.QueryString["ID"].Split('-');

			if (inputs.Length > 2)
			{
				parentFolderId = Convert.ToInt32(inputs[1]);
				folderId = Convert.ToInt32(inputs[2]);
			}

			
			if (targetUrl.Trim() == "")
			{
				lStatus.Text = "Please enter a valid feed URL.";
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}

			if (targetUrl.Length > 255)
			{
				lStatus.Text = "The feed URL you entered was too long. Please try again.";
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}

            if(targetUrl.ToLower().StartsWith("feed://"))
            {
                targetUrl = "http://" + targetUrl.Substring(7);
            }

			if (!targetUrl.StartsWith("http://") &&
				!targetUrl.StartsWith("https://"))
			{
				targetUrl = "http://" + targetUrl;
			}

			int feedID = -1;
			try
			{
				feedID = AddFeedHelper.AddFeed(folderId, targetUrl);
			}
			catch (Exception ex)
			{
				lStatus.Text = ex.Message;
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}

			// Send response

			if (folderId == 0)
			{
				CommunityServer.Controls.Modal.ClosePage(this.Page, String.Format(
					returnValue, 
					Page.Request.QueryString["ID"],
					Context.Response.ApplyAppPathModifier("~/reader/FolderXml.ashx?ParentFolderId=0"),
					FeedReaderResourceManager.GetString("reader_root_node_my_feeds").Replace("'", "\\'"),
					FeedReaderResourceManager.GetString("reader_root_node_my_feeds").Replace("'", "\\'"),
					"null",
					"null"
					));
			}
			else
			{
				System.Collections.ArrayList folders = FeedReaderDataProvider.Instance().GetFolders(userId, parentFolderId);
				bool folderFound = false;

				foreach (Folder f in folders)
				{
					if (f.FolderId == folderId)
					{
						folderFound = true;
						CommunityServer.Controls.Modal.ClosePage(this.Page, String.Format(
							returnValue, 
							Page.Request.QueryString["ID"],
							Context.Response.ApplyAppPathModifier("~/reader/FolderXml.ashx?ParentFolderId=" + f.FolderId.ToString()),
							(f.FolderName == null || f.FolderName.Trim() == "" ? "Unknown folder name" : f.FolderName + (f.UnreadCount > 0 ? " (" + f.UnreadCount + ")" : "")).Replace("'", "\\'"),
							(f.FolderName == null || f.FolderName.Trim() == "" ? "An error occurred to where no folder name was recorded for this folder. Please try to delete it and recreate it if possible." : f.FolderName + (f.UnreadCount > 0 ? " (" + f.UnreadCount + ")" : "")).Replace("'", "\\'"),
							f.UnreadCount > 0 ? "'UnreadTreeNode'" : "null",
							f.UnreadCount > 0 ? "'UnreadHoverTreeNode'" : "null"
							));

						break;
					}
				}

				if (!folderFound)
					CommunityServer.Controls.Modal.ClosePage(this.Page);
			}
				
		}

		private readonly string returnValue = "['{0}',[['ContentCallbackUrl','{1}'],['Text','{2}'],['ToolTip','{3}'],['CssClass',{4}],['HoverCssClass',{5}]]]";

		#endregion


	}
}
