using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Telerik.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    private static string connstr = ConfigurationManager.ConnectionStrings["HelpDesk2ConnectionString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadTreeViewUsers();
            LoadGridData();
            RadMenu1.LoadContentFile("menu.xml");
            DateTime date = new DateTime(2008, 10, 1);
            RadCalendar1.FocusedDate = date;
            CustomizeCalendar();
        }
      
    }

    private void LoadTreeViewUsers()
    {       
        SqlConnection dbCon = new SqlConnection(connstr);

        dbCon.Open();
        string strSelect = " SELECT UserID,Name,Image From Users ORDER BY Name";
        SqlDataAdapter adapter = new SqlDataAdapter(strSelect, dbCon); 
        DataSet ds = new DataSet();
        
		try
        {
           adapter.Fill(ds);
        }
        finally
        {
			dbCon.Close();
        }
        
        foreach(DataRow dbRow in ds.Tables[0].Rows)
        {
            if (!dbRow.IsNull("UserID"))
            {
                RadTreeNode node = new RadTreeNode();
				node.Text = dbRow["Name"].ToString(); 
                node.Value = dbRow["UserID"].ToString();                
                node.ImageUrl = "Img/" + dbRow["Image"].ToString();                              
                
                RadTreeView1.Nodes[0].Nodes.Add(node);
                LoadTreeViewUserProducts(dbRow, node);
				node.Attributes["id"] = dbRow["UserID"].ToString();
				this.TreeViewRadToolTipManager.TargetControls.Add(dbRow["UserID"].ToString(), true);
            }
        }

        RadTreeView1.Nodes[0].Expanded = true;
    }
    private void LoadTreeViewUserProducts(DataRow dbRow, RadTreeNode node)
    {        
        SqlConnection dbCon = new SqlConnection(connstr);
        dbCon.Open();

        string strSelect = @"   SELECT P.ProductID as ProductID , U.UserID as [User], P.Name as Product 
                                    FROM Users U 
                                INNER JOIN Threads T 
                                    ON U.userID = T.userID  
                                INNER JOIN Products P 
                                    ON T.ProductID = P.ProductID
                                GROUP BY P.Name,U.UserID,P.ProductID";
        SqlDataAdapter adapter = new SqlDataAdapter(strSelect, dbCon);
        DataSet ds = new DataSet();
        try
        {
            adapter.Fill(ds);
        }
        finally
        {
            dbCon.Close();
        }
        foreach (DataRow childRow in ds.Tables[0].Rows)
        {
            if (dbRow["UserID"].ToString() == childRow["User"].ToString())
            {
                RadTreeNode childNode = new RadTreeNode();
                childNode.Text = childRow["Product"].ToString();
                childNode.Value = childRow["ProductID"].ToString();
                node.Nodes.Add(childNode);
            }
        }
    }

	protected void RadTreeView1_NodeClick(object o, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        if (e.Node.Level > 0)
        {
            SelectNode(e.Node);
        }
    }

    protected void SelectNode(RadTreeNode selectedNode)
    {
        RadGrid1.DataSourceID = String.Empty;
        RadGrid1.DataSource = GetAllMessagesByProduct(selectedNode);
        RadGrid1.DataBind();
    }

    public DataTable GetAllMessagesByProduct(RadTreeNode selectedNode)
    {
        SqlConnection dbCon = new SqlConnection(connstr);
        dbCon.Open();
        string strSelect = String.Empty;
        if (selectedNode.Level == 1) // users
        {
            strSelect = @"  SELECT *,P.Name as Product
                                FROM Users U 
                            INNER JOIN Messages M 
                                ON U.UserID = M.Sender  
                            INNER JOIN Threads T 
                                ON M.ThreadID = T.ThreadID 
                            INNER JOIN Products P 
                                ON P.ProductID=T.productID 
                            WHERE T.userID = @ID";   
        }
        else if (selectedNode.Level == 2) // user products
        {
            strSelect = @"  SELECT *,P.Name as Product
                                FROM Users U 
                            INNER JOIN Messages M 
                                ON U.UserID = M.Sender  
                            INNER JOIN Threads T 
                                ON M.ThreadID = T.ThreadID 
                            INNER JOIN Products P 
                                ON P.ProductID=T.productID 
                            WHERE T.ProductID = @ID and T.UserID=@UserID";
        }
       
        SqlCommand comm = new SqlCommand(strSelect, dbCon);
        comm.CommandType = CommandType.Text;

        SqlParameter id = new SqlParameter("@ID", selectedNode.Value);
        comm.Parameters.Add(id);

        SqlParameter userid = new SqlParameter("@UserID", selectedNode.ParentNode.Value);
        comm.Parameters.Add(userid);

        SqlDataAdapter adapter = new SqlDataAdapter(comm);
        DataSet ds = new DataSet();

        try
        {
            adapter.Fill(ds);
        }
        finally
        {
            dbCon.Close();
        }
      
        return ds.Tables[0];
    }
    public void CustomizeCalendar()
    {
        SqlConnection dbCon = new SqlConnection(connstr);
        dbCon.Open();
        string strSelect  = @"  SELECT Distinct Date FROM Messages";
       

        SqlCommand comm = new SqlCommand(strSelect, dbCon);
        comm.CommandType = CommandType.Text;
        SqlDataReader  reader = comm.ExecuteReader();
        while (reader.Read())
        {
            RadCalendarDay day =  new RadCalendarDay();
            day.Date =  (DateTime)reader[0];
            day.ItemStyle.CssClass ="radCalSelect_" +  Page.Theme;
            RadCalendar1.SpecialDays.Add(day);
        }
       
        dbCon.Close();

    }
    public DataTable GetAllMessagesBySender(string val)
    {
        SqlConnection dbCon = new SqlConnection(connstr);
        dbCon.Open();
        string strSelect = @"    SELECT  *,P.Name as Product 
                                    FROM Users U 
                                 INNER JOIN Messages M 
                                    ON U.UserID = M.Sender 
                                 INNER JOIN Threads T 
                                    ON M.ThreadID = T.ThreadID 
                                 INNER JOIN Products P 
                                    ON P.ProductID=T.productID 
                                 WHERE M.Sender = @ID";
        
        SqlCommand comm = new SqlCommand(strSelect, dbCon);
        comm.CommandType = CommandType.Text;

        SqlParameter id = new SqlParameter("@ID", val);
        comm.Parameters.Add(id);

        SqlDataAdapter adapter = new SqlDataAdapter(comm);
        DataSet ds = new DataSet();

        try
        {
            adapter.Fill(ds);
        }
        finally
        {
            dbCon.Close();
        }
      
        return ds.Tables[0];
    }

    public void LoadGridData()
    {
        RadTreeNode firstNode = RadTreeView1.Nodes[0].Nodes[0];
        firstNode.Selected = true;
        SelectNode(firstNode);
    }
    
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem dataItem = (GridDataItem)e.Item;
            Label lblDate = (Label)e.Item.FindControl("itemLabelDate");
            string date = ((DateTime)DataBinder.Eval(e.Item.DataItem, "Date")).ToShortDateString();
            lblDate.Text = date;

            HyperLink hlReply = (HyperLink)e.Item.FindControl("hlReply");
            string replyMessage = DataBinder.Eval(e.Item.DataItem, "MessageID").ToString().Insert(0, "Compose.aspx?MessageID=");
            hlReply.NavigateUrl = String.Format("javascript:ShowMessage('{0}');", replyMessage);          
        }
    }    
   

    private string GetText(int messageID)
    {
        string text = String.Empty;
        SqlConnection dbCon = new SqlConnection(connstr);
        string  strSelect = @"   SELECT  Text
                                    FROM Messages 
                                 WHERE messageID = @ID ";
       
        SqlCommand comm = new SqlCommand(strSelect, dbCon);
        comm.CommandType = CommandType.Text;

        SqlParameter id = new SqlParameter("@ID", messageID);
        comm.Parameters.Add(id);
        dbCon.Open();
        try
        {
            text = comm.ExecuteScalar().ToString();
        }
        finally
        {
            dbCon.Close();
        }

        return text;
    }

    private bool IsSelectedDate(DateTime date)
    {
        bool IsDateWithMessage = false;
        SqlConnection dbCon = new SqlConnection(connstr);
        string strSelect = @"    SELECT  *,P.Name as Product 
                                    FROM Users U 
                                 INNER JOIN Messages M 
                                    ON U.UserID = M.Sender 
                                 INNER JOIN Threads T 
                                    ON M.ThreadID = T.ThreadID 
                                  INNER JOIN Products P 
                                    ON P.ProductID=T.productID 
                                    WHERE M.Date =@date ";

        SqlCommand comm = new SqlCommand(strSelect, dbCon);
        SqlDataReader reader;
        comm.CommandType = CommandType.Text;

        SqlParameter sqldate = new SqlParameter("@date", date);
        comm.Parameters.Add(sqldate);
        dbCon.Open();
        reader = comm.ExecuteReader();

        try
        {
            IsDateWithMessage = reader.Read();
        }
        finally
        {
            dbCon.Close();
        }

        return IsDateWithMessage;
    }

    public void RadCombobox_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
    {
        const int ITEMS_PER_REQUEST = 10;
        RadComboBox combo = (RadComboBox)o;

        SqlConnection dbCon = new SqlConnection(connstr);
        dbCon.Open();

        string text = e.Text;
        string sql = "SELECT * from Users WHERE Name LIKE ''+@name+'%'";

        SqlCommand comm = new SqlCommand(sql, dbCon);
        comm.CommandType = CommandType.Text;

        SqlParameter name = new SqlParameter("@name", text.Replace("'", "''"));
        comm.Parameters.Add(name);

        SqlDataAdapter adapter = new SqlDataAdapter(comm);
        DataTable dt = new DataTable();
        try
        {
            adapter.Fill(dt);
        }
        finally
        {
            dbCon.Close();
        }

        int start = e.NumberOfItems;
        int end = Math.Min(start + ITEMS_PER_REQUEST, dt.Rows.Count);

        for (int i = start; i < end; i++)
        {
            RadComboBoxItem item = new RadComboBoxItem(dt.Rows[i]["Name"].ToString());
            item.Value = dt.Rows[i]["UserID"].ToString();
            combo.Items.Add(item);            
        }
        
        e.Message = end < dt.Rows.Count ? "items " + (start+1) + " -" + (end+1) + " from " + dt.Rows.Count : "";
    }

    protected void RadCombobox_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox combo = (RadComboBox)o;        
        
        RadGrid1.DataSourceID = String.Empty;
        RadGrid1.DataSource = GetAllMessagesBySender(combo.SelectedValue);
        RadGrid1.DataBind();
    }

    protected void RadCalendar1_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
    {
        RadGrid1.DataSourceID = "SqlDataSource2";
    }
	protected void CustomizeDay(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
    {
        DateTime CurrentDate = e.Day.Date;
        if (IsSelectedDate(CurrentDate))
        {
            TableCell currentCell = e.Cell;
			currentCell.CssClass = "radCalSelect_" +  Page.Theme;
        }
    }

    protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
        RadGrid messageGrid = (RadGrid)sender;
        if (messageGrid.Items.Count > 0 && messageGrid.SelectedItems.Count==0)
        {
            GridDataItem selectedItem = (GridDataItem)messageGrid.Items[0];
            messageGrid.SelectedIndexes.Add(0);
            LoadMessage(selectedItem);
        }
        else if (messageGrid.Items.Count == 0)
        {
            LoadEmptyMessage();
        }
    }

    public void LoadMessage(GridDataItem selectedItem)
    {
        int messageID = Int32.Parse(selectedItem["MessageId"].Text);
        Label itemLabel = (Label)selectedItem.FindControl("itemLabel");
        Label itemLabelDate = (Label)selectedItem.FindControl("itemLabelDate");

        lblThreadTitle.Text = itemLabel.Text;
        lblMessageDate.Text = itemLabelDate.Text;
        lblText.Text = GetText(messageID);
    }

    public void LoadEmptyMessage()
    {
        lblThreadTitle.Text = String.Empty;
        lblMessageDate.Text = String.Empty;
        lblText.Text = String.Empty;
    }

	protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
	{

		int selectedIndex = Convert.ToInt32(e.Argument);

		if (selectedIndex == -1)
		{
			selectedIndex = Convert.ToInt32(RadGrid1.SelectedIndexes[0]);
		}

		RadGrid1.Items[selectedIndex].Selected = true;
		LoadMessage(RadGrid1.Items[selectedIndex]);
	}
}
