using System;
using System.Data; 
using System.Data.SqlClient; 
using System.Collections; 
using Meta.Web;
using Meta.Web.Security;
using Meta.Data.Member;
using Meta.Data;

namespace MetaSite.Components.Providers
{
	/// <summary>
	/// PostProvider”£
	/// </summary>
	public class CommonDataProvider
	{
		#region"common"		
 
		

		#endregion

		#region"Index"

		public static DataTable GetIndexs()
		{			
			DataProvider table = new DataProvider("ms_Imgindex");
			DataTable t = table.GetOrderData("postdate desc" ).DefaultTable;			
			return t;
		}

		public static ImageIndex FormatIndex(DataRow dr)
		{
			ImageIndex index = new ImageIndex();			
		
			index.ImageUrl = (string)dr["imgurl"];
			index.PostId = int.Parse(dr["postid"].ToString());
			index.Subject = (string)dr["subject"];
			index.Comment = (string)dr["comment"];
			index.PostDate = DateTime.Parse(dr["postdate"].ToString());

			return index;
		}

		public static ImageIndex GetIndex(int postId)
		{
			DataProvider table = new DataProvider("ms_Imgindex");
			DataTable t = table.GetData("postid = " + postId.ToString()).DefaultTable;	
		
			if (t.Rows.Count == 0)
				return null;

			DataRow dr = t.Rows[0];

			return FormatIndex(dr);			
		}

		public static void CreateIndex(ImageIndex index)
		{	
			DataProvider table = new DataProvider("ms_Imgindex");

			table.Insert( index.PostId,index.ImageUrl,index.Subject,index.Comment,index.PostDate);  			
		}

		public static void UpdateIndex (ImageIndex index)
		{
			DataProvider table = new DataProvider("ms_Imgindex");
			
			string sets = " imgurl = '" + index.ImageUrl +"'";
			
			string w = " postid="+index.PostId;			

			table.Update(sets,w); 
		}

		public static void DeleteIndex (int postId)
		{
			DataProvider.Execute("delete from ms_Imgindex where postid = " + postId.ToString());  			
		}

		#endregion
	
		#region"post"

		public static ArrayList GetNoApprovedPostsInForum()
		{
            string sql = "select distinct forumid, count(postid) as count from ms_posts where isApproved = 0 group by forumid";    

			SqlDataReader reader = (SqlDataReader)DataProvider.GetDataReader(sql);

			ArrayList has = new ArrayList(); 

			while( reader.Read())
			{
				int c = (int)reader.GetValue(1);

				if ( c>0)
			    	has.Add(new ForumPost(Forums.GetForum((int)reader.GetValue(0)),c));
			}

			return has;            
		}

		public static DataTable GetNoApprovedPosts(int forumId)
		{
			string sql = "isApproved = 0 and forumid ={0}";

			DataProvider table = new DataProvider("ms_Posts");
		
			return table.GetData(string.Format(sql,forumId.ToString())).DefaultTable;            
		}

		public static void Approve(int postid)
		{
			DataProvider.Execute("update ms_posts set IsApproved = 1 where postid = " +  postid.ToString()); 
		}

		public static void DeletePost(int postid)
		{
			Post p = GetPost(postid,false);
			if(p.PostLevel == 1)
			{
				DataProvider.Execute("update ms_forums set TotalPosts = TotalPosts-"+ p.Topic.TotalPosts +  
					" ,TotalTopics = TotalTopics-1 where forumid = " +  p.ForumId.ToString()); 

				DataProvider.Execute("delete from ms_Topics where topicid = " + p.TopicId);  
				DataProvider.Execute( "update ms_profile set TotalTopics = TotalTopics-1,"+
					" TotalPosts = TotalPosts - 1 where userid = " + p.User.UserId );  		
			}
			else
			{
                DataProvider.Execute("update ms_Topics set TotalPosts = TotalPosts -1 where topicid = "+ p.TopicId.ToString());   
				DataProvider.Execute( "update ms_profile set  TotalPosts = TotalPosts - 1 where userid = " + p.User.UserId );  
			}
			
			DataProvider.Execute("delete from ms_posts  where ParentId = " +  postid.ToString()); 
		}


		public static Post GetPost(int postid,bool trackViews)
		{
			DataProvider table = new DataProvider("ms_Posts");
			DataTable t = table.GetData("postid = " + postid).DefaultTable; 
			if (t.Rows.Count == 0)
				return null;

			DataRow dr = t.Rows[0]; 
			Post p = new Post(); 

			p.PostId = (int)dr["PostId"];
			p.ParentId = (int)dr["ParentId"];
			p.TopicId = (int)dr["TopicId"];
			p.User = Users.GetUser((int)dr["userid"]);
			p.ForumId = (int)dr["ForumId"];
			p.SortOrder = (int)dr["SortOrder"];
			p.Subject = (string)dr["Subject"];
			p.PostDate = DateTime.Parse(dr["PostDate"].ToString());
			p.IsApproved = (bool)dr["IsApproved"];
			p.IsLocked = (bool)dr["IsLocked"];
			p.TotalViews = (int)dr["TotalViews"];
			p.Body = (string)dr["Body"];
			p.PostLevel = int.Parse(dr["PostLevel"].ToString());
			p.AppendText((string)dr["Propertys"]);

			if(trackViews)
			{
				int tv = p.TotalViews+1;
				DataProvider.Execute("update ms_posts set  TotalViews = " + tv + " where postid = " + p.PostId ); 
				tv = p.Topic.TotalViews+1; 
				DataProvider.Execute("update ms_topics set  TotalViews = "+ tv + " where topicid = " + p.TopicId ); 
			}

			return p;            
		}

		public static Post AddPost(Post post, User author)
		{
			DataProvider table = new DataProvider("ms_Topics");			

			if ( post.PostLevel == 1)
			{	
				DataProvider.Execute( "update ms_forums set TotalTopics = TotalTopics+1,"+
					" TotalPosts = TotalPosts + 1 where forumid = " + post.ForumId );  
				post.TopicId = table.Insert(post.ForumId,author.UserId,author.NickName,
					post.PostDate,post.PostDate,0,1,"");  

				DataProvider.Execute( "update ms_profile set TotalTopics = TotalTopics+1,"+
					" TotalPosts = TotalPosts + 1 where userid = " + post.User.UserId );  				
				
			}
			else
			{
				CommonData ud = table.GetData("TopicId = " + post.TopicId );
				DataRow dr = ud.DefaultTable.Rows[0];
				dr["PostDate"] = post.PostDate;						
				dr["TotalPosts"] = (int)dr["TotalPosts"] + 1;
				table.Update(ud);
				DataProvider.Execute( "update ms_forums set TotalPosts = TotalPosts + 1 where forumid = " + post.ForumId );  
				
				DataProvider.Execute( "update ms_profile set  TotalPosts = TotalPosts + 1 where userid = " + post.User.UserId );  
			}

			table = new DataProvider("ms_Posts");

			bool topPost = (post.ParentId == 0);		

			post.PostId = table.Insert(post.TopicId,post.ParentId,author.NickName,author.UserId,post.ForumId,post.SortOrder,
				post.Subject,post.PostDate,post.IsApproved,post.IsLocked,post.TotalViews,post.Body,post.PostLevel,post.ValueString);  

			if ( topPost)
			{				
				UpdatePost(post); 
			}
     
			return post;
		}
		
		public static DataTable GetPosts(int postId)
		{
	    	return GetPosts(postId,false);
		}

		public static DataTable GetPosts(int postId,bool admin)
		{			
			DataProvider table = new DataProvider("ms_Posts");

            int TopicId = (int)(table.GetData( " postId = " +  postId ).DefaultTable.Rows[0]["TopicId"]);

			if ( admin )
				return table.GetData( " TopicId = " + TopicId + " order by SortOrder ").DefaultTable;   
			else 
			    return table.GetData( " IsApproved = 1 and TopicId = " + TopicId + " order by SortOrder ").DefaultTable;   
		}

		public static void UpdatePost(Post post) 
		{
			DataProvider table = new DataProvider("ms_Posts");
			CommonData ud = table.GetData("postId = " + post.PostId );
		
			if ( ud.DefaultTable.Rows.Count == 0)
				return;

			DataRow dr = ud.DefaultTable.Rows[0];

			dr["ParentId"] = post.ParentId;
			dr["SortOrder"] = post.SortOrder;
			dr["Subject"] = post.Subject ;
			dr["PostDate"] = post.PostDate;
			dr["IsApproved"] = post.IsApproved;
			dr["IsLocked"] = post.IsLocked;
			dr["TotalViews"] = post.TotalViews;
			dr["Body"] = post.Body;			
			dr["Propertys"] = post.ValueString;

			table.Update(ud); 
		}

		#endregion

		#region"resources"

		public static Resource GetResource(int id) 
		{
			DataProvider table = new DataProvider("ms_Resources");	
                        
			DataTable tb = table.GetData("id="+id.ToString()).DefaultTable;
			
			DataRow dr = tb.Rows[0];

			Resource r = new Resource();
 
			r.Id = id;
			r.Code = dr["code"].ToString();
			r.SortOrder = int.Parse(dr["sortorder"].ToString());
			r.Title = dr["title"].ToString();
			r.Text = dr["data"].ToString();
			r.Style = int.Parse(dr["style"].ToString());
			
			return r;
		}

		public static Resource GetResource(string code) 
		{
			DataProvider table = new DataProvider("ms_Resources");	                        
			DataTable tb = table.GetData("code='"+ code +"'").DefaultTable;			
			DataRow dr = tb.Rows[0];
			Resource r = new Resource();
 
			r.Id = int.Parse(dr["id"].ToString());;
			r.Code = dr["code"].ToString();
			r.SortOrder = int.Parse(dr["sortorder"].ToString());
			r.Title = dr["title"].ToString();
			r.Text = dr["data"].ToString();
			r.Style = int.Parse(dr["style"].ToString());			
			return r;
		}

        public static int ResourcesCount()
        {
            return (int)DataProvider.Execute("select count( id ) from  ms_Resources");  
        }

        public static DataTable GetResources( int psize,int pid) 
		{
			DataProvider table = new DataProvider("ms_Resources");

            DataTable tb = table.GetData(psize,pid, "", "sortorder").DefaultTable;			
			
			return tb;
		}

		public static DataTable GetResources(int sty) 
		{
			DataProvider table = new DataProvider("ms_Resources");	
                        
			DataTable tb = table.GetData("style="+ sty.ToString() +" order by sortorder").DefaultTable;			
			
			return tb;
		}

		public static void DeleteResource(int id)
		{			
			DataProvider.Execute("delete from ms_Resources where id = "+ id ); 
		}
		public static Resource AddResource(Resource r)
		{
			DataProvider dp = new DataProvider("ms_Resources"); 

			int max = -1;
			try
			{
				max =  (int)dp.GetSpecialValue(Special.max,"sortorder");
			}
			catch{}			
		
			r.SortOrder = max+1;
			r.Id = dp.Insert(r.Title,r.Text,max+1,r.Code,r.Style);

			return r;
		}	

		public static void UpdateResource(Resource r)
		{			
			DataProvider table = new DataProvider("ms_Resources");
			
			string sets = " title = '" + r.Title +"'";
			sets +=  ", data = '" + r.Text +"'";
			sets +=  ", sortorder = " + r.SortOrder.ToString();		
			sets +=  ", code = '" + r.Code.ToString()+"'";	
			sets +=  ", style = " + r.Style.ToString();	

			string w = " id="+r.Id;		
			table.Update(sets,w); 
		}

		#endregion

		#region"links"

		public static DataTable GetLinks() 
		{
			DataProvider table = new DataProvider("ms_Links");	
                        
			DataTable tb = table.GetOrderData("sortorder").DefaultTable;			
			
			return tb;
		}
		public static void DeleteLink(int linkId)
		{
            DataProvider.Execute("delete from ms_links where linkid = "+ linkId); 
		}
		public static void AddLink(string title,string url)
		{
			DataProvider dp = new DataProvider("ms_Links"); 

			int max = -1;
			try
			{
				max = (int)dp.GetSpecialValue(Special.max,"sortorder");
			}
			catch{}

			dp.Insert(title,url,max+1);
		}

		public static void ChangeLinkSortOrder(int linkId,bool moveUp)
		{
			DataProvider dp = new DataProvider("ms_Links"); 
			int sort = (int)DataProvider.Execute("select sortorder from ms_Links where linkId = " + linkId);

			string sql = "select top 1 linkid,sortorder from  ms_Links where sortorder {0} order by sortorder {1}";  
			string e = moveUp? "<"+sort:">"+sort;
			string o = moveUp? "desc":"";
			
			SqlDataReader vals = (SqlDataReader)DataProvider.GetDataReader(string.Format(sql,e,o));
			
			if (!vals.Read())
				return;
		
			int sort2 = int.Parse(vals.GetValue(1).ToString());
			int fid = int.Parse(vals.GetValue(0).ToString());

			vals.Close(); 
			
			sql = "update ms_Links set sortorder = {0} where linkId={1} update ms_Links set  sortorder = {2} where linkid = {3}";

			DataProvider.Execute(string.Format(sql,sort2,linkId,sort,fid));
		}


		#endregion

		#region"images"

		public static _Image AddImage(_Image img) 
		{
			DataProvider table = new DataProvider("ms_Images");	

			img.ImageId = table.Insert( img.FileName,img.RealFileName,img.ContentType,img.ContentSize,img.CreationDate);  
   
			return img;			
		}

		public static void UpdateImage(_Image img)
		{
			DataProvider table = new DataProvider("ms_Images");
			CommonData ud = table.GetData("imageid = " + img.ImageId );
		
			if ( ud.DefaultTable.Rows.Count == 0)
				return;

			DataRow dr = ud.DefaultTable.Rows[0];

			dr["FileName"] = img.FileName;
			dr["RealFileName"] = img.RealFileName;
			dr["ContentType"] = img.ContentType ;
			dr["ContentSize"] = img.ContentSize;			
			dr["CreationDate"] = img.CreationDate;		

			table.Update(ud);             
		}

		public static void DeleteImage(_Image img)
		{
			DataProvider.Execute("delete from ms_images where imageId = " +img.ImageId );		
		}

		public static DataTable GetImages() 
		{
			DataProvider table = new DataProvider("ms_Images");	
			
			return table.GetData().DefaultTable;
		}
		
		public static string[] GetImages(string filename) 
		{
			DataProvider table = new DataProvider("ms_Images");	

			DataTable tb = table.GetData(" FileName = '" + filename + "'").DefaultTable;

			int count = 0;

			if ( ( count = tb.Rows.Count) == 0)
				return new string[0]; 

			string[] imgs = new string[count];

			for(int i=0; i < count;i++)
			{
				imgs[i] = tb.Rows[0]["RealFileName"].ToString();
			}		
			
			return imgs; 
		}		
	
		#endregion

		#region "Topic"

        public static int GetTopicsCount(int forumId)
        {
            DataProvider table = new DataProvider("ms_Topics");
            table.JoinTable("ms_Posts", new string[] { "ms_Topics.TopicId = ms_posts.TopicId" }, "postid", "Subject");

            return (int)table.GetSpecialValue( Special.count, 0,"ms_Topics.ForumId = " + forumId +
                " and PostLevel=1 and IsApproved = 1 "); 
        }

        private static string getForumsStr(int forumId )
        {
            string sq = "";

            DataTable t = GetForumGroup(forumId);
            foreach (DataRow dr in t.Rows)
            {
                Forum f = FormatForum(dr);
                sq += "," + f.ForumId;

                if (f.IsGroup)
                    sq += getForumsStr(f.ForumId);                
            }

            return sq;
        }


		public static DataTable GetTopics(int forumId,int top) 
		{
            string sql = getForumsStr(forumId);
            if (sql.Length > 1)
                sql = " and  ms_forums.parentid in (" + forumId + sql + ") "; 

			DataProvider table = new DataProvider("ms_Topics");	
			table.JoinTable("ms_Posts",new string[]{ "ms_Topics.TopicId = ms_posts.TopicId"},"postid","Subject");
            table.JoinTable("ms_Forums", new string[] { "ms_Forums.ForumId = ms_Topics.ForumId" }, "parentid");
                        
			DataTable tb = table.GetData("ms_Topics.ForumId = " + forumId + sql +
                " and PostLevel=1 and IsApproved = 1 order by ms_Topics.postdate desc",top).DefaultTable;			
			
			return tb;
		}
    

        public static DataTable GetHotTopics(int forumId, int top)
        {
            string sql = getForumsStr(forumId);
            if (sql.Length > 1)
                sql = " and  ms_forums.parentid in (" + forumId + sql + ") "; 

            DataProvider table = new DataProvider("ms_Topics", "PostAuthor", "forumid");
            table.JoinTable("ms_Posts", new string[] { "ms_Topics.TopicId = ms_posts.TopicId" }, "postid", "Subject");
            table.JoinTable("ms_forums", new string[] { "ms_forums.forumid = ms_posts.forumid" }, "name");

            DataTable tb = table.GetData("ms_forums.forumid = " + forumId.ToString() + sql + " and PostLevel=1 and  " +
                " IsApproved = 1 and " +
                " DATEADD(m,2,ms_posts.postdate) > getdate() order by  ms_Topics.TotalViews desc", top).DefaultTable;

            return tb;
        }
       
       
       /*public static DataTable GetTopics(int forumId, int top)
        {          
            DataProvider table = new DataProvider("ms_Topics");
            table.JoinTable("ms_Posts", new string[] { "ms_Topics.TopicId = ms_posts.TopicId" }, "postid", "Subject");           

            DataTable tb = table.GetData("ms_Topics.ForumId = " + forumId +
                " and PostLevel=1 and IsApproved = 1 order by ms_Topics.postdate desc", top).DefaultTable;

            return tb;
        }*/

       public static DataTable GetTopics(int forumId, int psize, int pid)
        {
            DataProvider table = new DataProvider("ms_Topics");
            table.JoinTable("ms_Posts", new string[] { "ms_Topics.TopicId = ms_posts.TopicId" }, "postid", "Subject");

            DataTable tb = table.GetData(psize,pid, "ms_Topics.ForumId = " + forumId + " and " +
                "PostLevel=1 and IsApproved = 1 order by ms_Topics.postdate desc").DefaultTable;

            return tb;
        }

		public static DataTable GetHotTopics(ForumType type,int top) 
		{
            DataProvider table = new DataProvider("ms_Topics", "PostAuthor", "forumid");	
			table.JoinTable("ms_Posts",new string[]{ "ms_Topics.TopicId = ms_posts.TopicId"},"postid","Subject");
			table.JoinTable("ms_forums",new string[]{ "ms_forums.forumid = ms_posts.forumid"},"name");
                        
			DataTable tb = table.GetData("ms_forums.Forumtype = "+((int)type).ToString() + " and PostLevel=1 and  IsApproved = 1 and "+
                " DATEADD(m,2,ms_posts.postdate) > getdate() order by  ms_Topics.TotalViews desc", top).DefaultTable;			
			
			return tb;
		}

        /*public static DataTable GetHotTopics(int forumId,int top)
        {
            DataProvider table = new DataProvider("ms_Topics", "PostAuthor", "forumid");
            table.JoinTable("ms_Posts", new string[] { "ms_Topics.TopicId = ms_posts.TopicId" }, "postid", "Subject");
            table.JoinTable("ms_forums", new string[] { "ms_forums.forumid = ms_posts.forumid" }, "name");

            DataTable tb = table.GetData("ms_forums.forumid = " + forumId.ToString() + " and PostLevel=1 and  " +
                " IsApproved = 1 and "+
                " DATEADD(m,2,ms_posts.postdate) > getdate() order by  ms_Topics.TotalViews desc", top).DefaultTable;

            return tb;
        }*/



		public static Topic GetTopic(int TopicId)
		{					
			DataProvider table = new DataProvider("ms_Topics");		
 
			DataTable tb = table.GetData( " TopicId = " + TopicId ).DefaultTable;

			if (tb.Rows.Count == 0)
				return null;

			DataRow dr = tb.Rows[0]; 		
			

			return FormatTopic(dr);            
		}

		public static Topic FormatTopic(DataRow dr)
		{
			Topic t = new Topic();				
			t.TopicId = (int)dr["TopicId"];
			t.User = Users.GetUser((int)dr["userid"]);
			t.ForumId = (int)dr["ForumId"];				
			t.PostDate = DateTime.Parse(dr["PostDate"].ToString());				
			t.TopicDate = DateTime.Parse(dr["TopicDate"].ToString()) ;				
			t.TotalViews = (int)dr["TotalViews"];		
			t.TotalPosts = (int)dr["TotalPosts"];		
			t.AppendText((string)dr["Propertys"]);

			return t;            
		}

		#endregion

		#region"forums"

		public static DataTable GetForumGroup()
		{			
			DataProvider table = new DataProvider("ms_Forums");
			DataTable t = table.GetOrderData(" isgroup = 0 ","SortOrder" ).DefaultTable;			
			return t;
		}

        public static DataTable GetForumGroup(int parentId)
        {
            DataProvider table = new DataProvider("ms_Forums");
            DataTable t = table.GetOrderData("parentid="+parentId,"SortOrder").DefaultTable;
            return t;
        }

        public static DataTable GetForumGroup(int parentId,bool group)
        {
            string grp = " and isgroup = "+ (group ? 1:0); 
            DataProvider table = new DataProvider("ms_Forums");
            DataTable t = table.GetOrderData("parentid=" + parentId + grp, "SortOrder").DefaultTable;
            return t;
        }

        //
        public static DataTable GetForumGroup(int type, int group)
        {
            string grp = ( group > 1 || group < 0) ? "":" and isgroup = " + group.ToString(); 
            DataProvider table = new DataProvider("ms_Forums");
            DataTable t = table.GetOrderData("forumtype=" + type + " and parentid=-1" + grp, "SortOrder").DefaultTable;
            return t;
        }

		public static Forum FormatForum(DataRow dr)
		{
			Forum forum = new Forum();
			
			forum.ForumId = int.Parse(dr["ForumId"].ToString());
			forum.Name = (string)dr["Name"];
			forum.IsActive = (bool)dr["IsActive"];				
			forum.Description = (string)dr["Description"];
			forum.SortOrder = (int)dr["SortOrder"];
			forum.CreationDate = DateTime.Parse(dr["creationdate"].ToString());  
			forum.TotalTopics = (int)dr["TotalTopics"];
			forum.TotalPosts = (int)dr["TotalPosts"];
			forum.IsSearchable = (bool)dr["IsSearchable"];		
			forum.ForumType = (ForumType)dr["ForumType"];
            forum.ParentId  = (int)dr["ParentId"];
            forum.IsGroup = (bool)dr["isgroup"]; 	

			return forum;
		}

		public static Forum GetForum(int forumId)
		{
			DataProvider table = new DataProvider("ms_Forums");
			DataTable t = table.GetData("ForumId = " + forumId.ToString()).DefaultTable;	
		
			if (t.Rows.Count == 0)
				return null;

			DataRow dr = t.Rows[0];

			return FormatForum(dr);			
		}

		public static Forum CreateForum(string name,ForumType type,int parentId,bool group)
		{			
			DataProvider table = new DataProvider("ms_Forums");
			object o = table.GetSpecialValue(Special.max,"sortorder");
  
			int max = 0;
			try
			{
				max = o==null? 0:(int)o+1;
			}
			catch{}

			Forum f = new Forum();
 
			f.CreationDate = DateTime.Now;
			f.Description = string.Empty;
			f.ForumType = type;
			f.IsActive = true;
			f.IsSearchable = true;
			f.TotalPosts = 0;
			f.TotalTopics = 0;
			f.Name = name;
			f.SortOrder = max;
            f.ParentId = parentId;
            f.IsGroup = group;


            f.ForumId = table.Insert(f.Name, f.Description, (int)f.ForumType, f.CreationDate, max, 1, 1, 0, 0, parentId, group);    			

			return f;	
		}

		public static void UpdateForum (Forum forum)
		{
			DataProvider table = new DataProvider("ms_forums");
			
			string sets = " name = '" + forum.Name +"'";
			sets +=  ", Description = '" + forum.Description +"'";
			sets +=  ", ForumType = " + ((int)forum.ForumType).ToString();
			sets +=  ", IsActive = " + (forum.IsActive? "1":"0") ;
            sets += ", parentid = " + forum.ParentId;
            sets += ", isgroup = " + (forum.IsGroup ? 1:0);

			string w = " forumid="+forum.ForumId;			

			table.Update(sets,w); 
		}

		public static void DeleteForum (Forum forum)
		{
			DataProvider.Execute("delete from ms_forums where forumid = " + forum.ForumId);  			
		}

		public static void ChangeForumSortOrder(int forumId,bool moveUp)
		{
			DataProvider dp = new DataProvider("ms_forums"); 
			int sort = (int)DataProvider.Execute("select sortorder from ms_forums where forumid = " + forumId );

			string sql = "select top 1 forumid,sortorder from  ms_forums where sortorder {0} order by sortorder {1}";  
			string e = moveUp? "<"+sort:">"+sort;
			string o = moveUp? "desc":"";
			
			SqlDataReader vals = (SqlDataReader)DataProvider.GetDataReader(string.Format(sql,e,o));
			
			if (!vals.Read())
				return;
		
			int sort2 = int.Parse(vals.GetValue(1).ToString());
			int fid = int.Parse(vals.GetValue(0).ToString());

			vals.Close(); 
			
			sql = "update ms_forums set sortorder = {0} where forumid={1} update ms_forums set  sortorder = {2} where forumid = {3}";

			DataProvider.Execute(string.Format(sql,sort2,forumId,sort,fid));
		}

		public static void AddPermission (ForumPermission fp) 
		{
            DataProvider dp = new DataProvider("ms_Permissions"); 
			CommonData cd = dp.CreateEmptyData();
			DataRow dr = cd.NewRow();
			dr["forumid"] = fp.ForumId;
			dr["roleid"] = fp.RoleId;
			dr["AllowMask"] = System.Text.Encoding.Default.GetBytes(((long)fp.AllowMask).ToString());
			dr["DenyMask"] = System.Text.Encoding.Default.GetBytes(((long)fp.DenyMask).ToString());
 
			cd.AddRow(dr);
			dp.Update(cd);
		}

		public static void RemovePermission (ForumPermission fp) 
		{
            DataProvider.Execute("delete from ms_Permissions where forumid = " + fp.ForumId + " and roleid = " + fp.RoleId);  	            
		}

        public static void RemovePermission(int forumId)
        {
            DataProvider.Execute("delete from ms_Permissions where forumid = " + forumId);  	 
        }

        public static void RemovePermission(Role r)
        {
            DataProvider.Execute("delete from ms_Permissions where roleid = " + r.RoleId);
        }

		public static void UpdatePermission (ForumPermission fp) 
		{
			DataProvider dp = new DataProvider("ms_Permissions"); 
			CommonData cd = dp.GetData(" forumid = " + fp.ForumId + " and roleid = " + fp.RoleId);  	
			DataRow dr = cd[0];
			
			dr["AllowMask"] = System.Text.Encoding.Default.GetBytes(((long)fp.AllowMask).ToString());
			dr["DenyMask"] = System.Text.Encoding.Default.GetBytes(((long)fp.DenyMask).ToString());

			dp.Update(cd);
		}

		public static ArrayList GetPermissions(int forumId)
		{
			DataProvider dp = new DataProvider("ms_Permissions"); 
			CommonData cd = dp.GetData(" forumid = " + forumId);

			ArrayList list = new  ArrayList();
  
			foreach( DataRow dr in cd.DefaultTable.Rows)
			{
				list.Add( FormatPermission(dr));
			}

			return list;
		}

		public static ForumPermission GetPermission(int forumId,int roleId)
		{
			DataProvider dp = new DataProvider("ms_Permissions"); 
			CommonData cd = dp.GetData(" forumid = " + forumId + " and roleId = "+ roleId );	
			return FormatPermission(cd[0]);
		}

		public static ForumPermission FormatPermission(DataRow dr)
		{
			ForumPermission fp = new ForumPermission(); 
			
			fp.ForumId = (int)dr["forumid"];
			fp.RoleId = (int)dr["roleid"];
			fp.AllowMask = (Permission)(long.Parse(System.Text.Encoding.Default.GetString((byte[])dr["AllowMask"])));
			fp.DenyMask = (Permission)(long.Parse(System.Text.Encoding.Default.GetString((byte[])dr["DenyMask"]))) ;
			fp.Name = DataProvider.Execute("select rolename from ms_roles where roleid = "+ fp.RoleId).ToString(); 

			return fp;
		}

		#endregion

		#region"Search"

		public static DataTable Search(int style,string keyWords,int mode)
		{
			string sql = "PostAuthor = '" + keyWords +"'";

			if (style == 1)
				sql = "Subject like '%" + keyWords +"%'";
            else if (style == 2)
            {
                string dt = DateTime.Today.ToString("d");
                try
                {
                    dt = DateTime.Parse(keyWords).ToString("d");
                }catch{}

                sql = "Postdate = " + dt;
            }
			
			string s = " and forumid in ( select forumid from ms_forums where ForumType = {0} and IsSearchable = 1)";

			sql += string.Format(s,mode.ToString());			

			DataProvider table = new DataProvider("ms_Posts");
			DataTable t = table.GetData(sql).DefaultTable;
 
			return t;
		}

		#endregion
	}
}
