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

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

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

		#region Private Members

		private HtmlInputFile uploadedFile;
		private Button btnSubmit;
		private StatusMessage lStatus;

		#endregion

		#region Constructor(s)

		public ImportOpml()
		{
			
		}

		#endregion

		#region Class Methods

		protected override void AttachChildControls()
		{
			uploadedFile = (HtmlInputFile) FindControl("uploadedFile");
			btnSubmit = (Button) FindControl("btnSubmit");
			lStatus = (StatusMessage) FindControl("lStatus");

			btnSubmit.Click += new EventHandler(btnSubmit_Click);

		}

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


		public override void DataBind()
		{
			base.DataBind ();
			
			CommunityServer.Controls.Head.AddTitle("Import OPML", this.Context);
		}

		#endregion

		private void btnSubmit_Click(object sender, EventArgs e)
		{
			string importStatus;


			if (uploadedFile.PostedFile == null)
			{
				lStatus.Text = "No file sent. Please try again.";
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}


			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(uploadedFile.PostedFile.InputStream);

				OpmlManager importer = new OpmlManager();

				importer.ImportOpml(doc);

				importStatus = "OPML importing has completed. ";

				if (importer.ErrorsOccurred)
				{
					importStatus += "<br/>There were some errors during the import.<br/>";
					importStatus += "<br/>";
					importStatus += "The following sites/folders had errors on import: ";
					importStatus += "<ul>";
					foreach (string site in importer.ErroredSites)
					{
						importStatus += "<li>" + site + "</li>";
					}
					importStatus += "</ul>";

					lStatus.Text = importStatus;
					lStatus.Success = false;
					lStatus.Visible = true;
				}
				else
				{
					importStatus += "Everything imported successfully.<br/>";
					lStatus.Text = importStatus;
					lStatus.Success = true;
					lStatus.Visible = true;
				}
				
			}
			catch (Exception exc)
			{
				importStatus = "Error importing OPML:<br/>" + exc.Message;
				lStatus.Text = importStatus;
				lStatus.Success = false;
				lStatus.Visible = true;
			}

			

		}
	}
}
