using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Meta.Web;
using Meta.Web.Controls; 
using Meta.Web.Controls.Template; 
using MetaSite.Components.Providers;  
using FreeTextBoxControls;

namespace MetaSite.Components.Controls.Views
{
	/// <summary>
	/// ResourceAdmin 。
	/// </summary>
	public class ResourceAdmin : BaseTemplateControl
	{		
		Button btOk;
		FreeTextBox DataText;
		TextBox txtTitle;
		TextBox txtOrder;
		TextBox txtCode;
		Label lbOrder;
		CheckBox ckShow;
	
		Resource res;

		bool IsEdit = false;	
	
		protected override void AttachChildControls()
		{
			if ( !AdminSettings.InAdminRoles("ManageResources"))
			{
				ForumPermission.RedirectOrExcpetion();			
			}

			Literal info = FindControl("Info") as Literal;
			info.Text = "<b>编辑资料</b>";

			txtTitle = FindControl("txtTitle") as TextBox;
			txtOrder = FindControl("txtOrder") as TextBox;
			txtCode = FindControl("txtCode") as TextBox;
			DataText = FindControl("DataText") as FreeTextBox;	
			lbOrder = FindControl("lbOrder") as Label;	
			ckShow = FindControl("ckShow") as CheckBox;	

			btOk = FindControl("btOk") as Button;
			btOk.Click += new EventHandler(btOk_Click);						
			
			Context.Items.Add(PageHead.key,"设置资料");

			ContextData cd = ContextData.Current; 
			int id = cd.GetIntFromQueryString("id",-2); 

			if(id > 0)
			{
				res = Resources.GetResource(id);
				txtTitle.Text = res.Title;
				DataText.Text = res.Text;
				txtOrder.Text = res.SortOrder.ToString();
				txtCode.Text = res.Code; 
				if ( res.Code.Length > 2 && res.Code.Substring(0,2)== "S-")
					txtCode.Enabled = false;
				ckShow.Checked = (res.Style == 1);
				IsEdit = true;
			}
			else
			{
				res = new Resource ();
				txtOrder.Visible = false;
				lbOrder.Visible = false;
			}			
		}		

		private void btOk_Click(object sender, EventArgs e)
		{
			res.Title = txtTitle.Text;
			res.Text = DataText.Text;
			res.Code = txtCode.Text; 
			res.Style = ckShow.Checked?1:0; 

			try
			{
				res.SortOrder = txtOrder.Text == string.Empty? 0: int.Parse(txtOrder.Text);  
			}
			catch{}
			
            if (IsEdit)
				Resources.UpdateResource(res);
			else
				Resources.AddResource(res);
 
			Page.Response.Redirect( Globals.UrlBase + "/admin/resources/manageresources.aspx"); 
		}
	}
}
