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

Partial Public Class DefaultVB
    Inherits System.Web.UI.Page
    Private Shared connstr As String = ConfigurationManager.ConnectionStrings("HelpDesk2ConnectionString").ConnectionString

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not Page.IsPostBack Then
            LoadTreeViewUsers()
            LoadGridData()
            RadMenu1.LoadContentFile("menu.xml")
            Dim [date] As New DateTime(2008, 6, 1)
            RadCalendar1.FocusedDate = [date]
            CustomizeCalendar()
        End If

    End Sub


    Private Sub LoadTreeViewUsers()
        Dim dbCon As New SqlConnection(connstr)

        dbCon.Open()
        Dim strSelect As String = " SELECT UserID,Name,Image From Users ORDER BY Name"
        Dim adapter As New SqlDataAdapter(strSelect, dbCon)
        Dim ds As New DataSet()
        Try
            adapter.Fill(ds)
        Finally
            dbCon.Close()
        End Try

        For Each dbRow As DataRow In ds.Tables(0).Rows
            If Not dbRow.IsNull("UserID") Then
                Dim node As 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()
                Me.TreeViewRadToolTipManager.TargetControls.Add(dbRow("UserID").ToString(), True)
            End If
        Next

        RadTreeView1.Nodes(0).Expanded = True
    End Sub

    Private Sub LoadTreeViewUserProducts(ByVal dbRow As DataRow, ByVal node As RadTreeNode)
        Dim dbCon As New SqlConnection(connstr)
        dbCon.Open()

        Dim strSelect As String = "   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 "
        Dim adapter As New SqlDataAdapter(strSelect, dbCon)
        Dim ds As New DataSet()
        Try
            adapter.Fill(ds)
        Finally
            dbCon.Close()
        End Try
        For Each childRow As DataRow In ds.Tables(0).Rows
            If dbRow("UserID").ToString() = childRow("User").ToString() Then
                Dim childNode As New RadTreeNode()
                childNode.Text = childRow("Product").ToString()
                childNode.Value = childRow("ProductID").ToString()
                node.Nodes.Add(childNode)
            End If
        Next
    End Sub

    Protected Sub RadTreeView1_NodeClick(ByVal o As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEventArgs)
        If e.Node.Level > 0 Then
            SelectNode(e.Node)
        End If
    End Sub

    Protected Sub SelectNode(ByVal selectedNode As RadTreeNode)
        RadGrid1.DataSourceID = String.Empty
        RadGrid1.DataSource = GetAllMessagesByProduct(selectedNode)
        RadGrid1.DataBind()
    End Sub

    Public Function GetAllMessagesByProduct(ByVal selectedNode As RadTreeNode) As DataTable
        Dim dbCon As New SqlConnection(connstr)
        dbCon.Open()
        Dim strSelect As String = [String].Empty
        If (selectedNode.Level = 1) Then
            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"
        ElseIf (selectedNode.Level = 2) Then
            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"
        End If

        Dim comm As New SqlCommand(strSelect, dbCon)
        comm.CommandType = CommandType.Text

        Dim id As New SqlParameter("@ID", selectedNode.Value)
        comm.Parameters.Add(id)

        Dim userid As New SqlParameter("@UserID", selectedNode.ParentNode.Value)
        comm.Parameters.Add(userid)

        Dim adapter As New SqlDataAdapter(comm)
        Dim ds As New DataSet()

        Try
            adapter.Fill(ds)
        Finally
            dbCon.Close()
        End Try

        Return ds.Tables(0)
    End Function

    Public Function GetAllMessagesBySender(ByVal val As String) As DataTable
        Dim dbCon As New SqlConnection(connstr)
        dbCon.Open()
        Dim strSelect As String = "    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"

        Dim comm As New SqlCommand(strSelect, dbCon)
        comm.CommandType = CommandType.Text

        Dim id As New SqlParameter("@ID", val)
        comm.Parameters.Add(id)

        Dim adapter As New SqlDataAdapter(comm)
        Dim ds As New DataSet()

        Try
            adapter.Fill(ds)
        Finally
            dbCon.Close()
        End Try

        Return ds.Tables(0)
    End Function

    Public Sub LoadGridData()
        Dim firstNode As RadTreeNode = RadTreeView1.Nodes(0).Nodes(0)
        firstNode.Selected = True
        SelectNode(firstNode)
    End Sub

    Protected Sub RadGrid1_ItemDataBound(ByVal sender As Object, ByVal e As GridItemEventArgs)
        If TypeOf e.Item Is GridDataItem Then
            Dim dataItem As GridDataItem = DirectCast(e.Item, GridDataItem)
            Dim lblDate As Label = DirectCast(e.Item.FindControl("itemLabelDate"), Label)
            Dim [date] As String = (DirectCast(DataBinder.Eval(e.Item.DataItem, "Date"), DateTime)).ToShortDateString()
            lblDate.Text = [date]

            Dim hlReply As HyperLink = DirectCast(e.Item.FindControl("hlReply"), HyperLink)
            Dim replyMessage As String = DataBinder.Eval(e.Item.DataItem, "MessageID").ToString().Insert(0, "ComposeVB.aspx?MessageID=")
            hlReply.NavigateUrl = [String].Format("javascript:ShowMessage('{0}');", replyMessage)
        End If
    End Sub

    Private Function GetText(ByVal messageID As Integer) As String
        Dim text As String = [String].Empty
        Dim dbCon As New SqlConnection(connstr)
        Dim strSelect As String = "  SELECT  Text" & _
                 "   FROM Messages " & _
                 "WHERE  MessageID = @ID "

        Dim comm As New SqlCommand(strSelect, dbCon)
        comm.CommandType = CommandType.Text

        Dim id As New SqlParameter("@ID", messageID)
        comm.Parameters.Add(id)
        dbCon.Open()
        Try
            text = comm.ExecuteScalar().ToString()
        Finally
            dbCon.Close()
        End Try

        Return text
    End Function


    Public Sub RadCombobox_ItemsRequested(ByVal o As Object, ByVal e As RadComboBoxItemsRequestedEventArgs)
        Const ITEMS_PER_REQUEST As Integer = 10
        Dim combo As RadComboBox = DirectCast(o, RadComboBox)

        Dim dbCon As New SqlConnection(connstr)
        dbCon.Open()

        Dim text As String = e.Text
        Dim sql As String = "SELECT * from Users WHERE Name LIKE ''+@name+'%'"

        Dim comm As New SqlCommand(sql, dbCon)
        comm.CommandType = CommandType.Text

        Dim name As New SqlParameter("@name", text.Replace("'", "''"))
        comm.Parameters.Add(name)

        Dim adapter As New SqlDataAdapter(comm)
        Dim dt As New DataTable()
        Try
            adapter.Fill(dt)
        Finally
            dbCon.Close()
        End Try

        Dim start As Integer = e.NumberOfItems
        Dim [end] As Integer = Math.Min(start + ITEMS_PER_REQUEST, dt.Rows.Count)

        Dim i As Integer = start
        While i < [end]
            Dim item As New RadComboBoxItem(dt.Rows(i)("Name").ToString())
            item.Value = dt.Rows(i)("UserID").ToString()
            combo.Items.Add(item)
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While

        If dt.Rows.Count > 0 Then
            e.Message = [String].Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", [end].ToString(), dt.Rows.Count.ToString())
        Else
            e.Message = "No matches"
        End If
    End Sub

    Protected Sub RadCombobox_SelectedIndexChanged(ByVal o As Object, ByVal e As RadComboBoxSelectedIndexChangedEventArgs)
        Dim combo As RadComboBox = DirectCast(o, RadComboBox)

        RadGrid1.DataSourceID = [String].Empty
        RadGrid1.DataSource = GetAllMessagesBySender(combo.SelectedValue)
        RadGrid1.DataBind()
    End Sub

    Protected Sub RadCalendar1_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.Calendar.SelectedDatesEventArgs)
        RadGrid1.DataSourceID = "SqlDataSource2"
    End Sub

    Public Sub CustomizeCalendar()
        Dim dbCon As New SqlConnection(connstr)
        dbCon.Open()
        Dim strSelect As String = "  SELECT Distinct Date FROM Messages"


        Dim comm As New SqlCommand(strSelect, dbCon)
        comm.CommandType = CommandType.Text
        Dim reader As SqlDataReader = comm.ExecuteReader()
        While reader.Read()
            Dim day As New RadCalendarDay()
            day.[Date] = DirectCast(reader(0), DateTime)
            day.ItemStyle.CssClass = "radCalSelect_" + Page.Theme
            RadCalendar1.SpecialDays.Add(day)
        End While

        dbCon.Close()

    End Sub

    Protected Sub RadGrid1_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        Dim messageGrid As RadGrid = DirectCast(sender, RadGrid)
        If messageGrid.Items.Count > 0 AndAlso messageGrid.SelectedItems.Count = 0 Then
            Dim selectedItem As GridDataItem = DirectCast(messageGrid.Items(0), GridDataItem)
            messageGrid.SelectedIndexes.Add(0)
            LoadMessage(selectedItem)
        ElseIf messageGrid.Items.Count = 0 Then
            LoadEmptyMessage()
        End If
    End Sub

    Public Sub LoadMessage(ByVal selectedItem As GridDataItem)
        Dim messageID As Integer = Int32.Parse(selectedItem("MessageId").Text)
        Dim itemLabel As Label = DirectCast(selectedItem.FindControl("itemLabel"), Label)
        Dim itemLabelDate As Label = DirectCast(selectedItem.FindControl("itemLabelDate"), Label)

        lblThreadTitle.Text = itemLabel.Text
        lblMessageDate.Text = itemLabelDate.Text
        lblText.Text = GetText(messageID)
    End Sub

    Public Sub LoadEmptyMessage()
        lblThreadTitle.Text = [String].Empty
        lblMessageDate.Text = [String].Empty
        lblText.Text = [String].Empty
    End Sub

    Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
        Dim selectedIndex As Integer = Convert.ToInt32(e.Argument)
        If selectedIndex = -1 Then
            selectedIndex = Convert.ToInt32(RadGrid1.SelectedIndexes(0))
        End If
        RadGrid1.Items(selectedIndex).Selected = True
        LoadMessage(RadGrid1.Items(selectedIndex))
    End Sub
End Class
