Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common
Imports System.Data
Imports System.Collections.Generic


Partial Class Configurations_PageManagement
    Inherits AdminPage

    Private _cmd As DbCommand
    Private _db As Database
    Private WebCrawledPageCollection As New Dictionary(Of String, WebCrawledPage)


    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If Session("user") Is Nothing Then
                '#####################################
                'SESSION EXPIRED, SEND TO MAIN PAGE
                '#####################################
                Response.Redirect(Me.UnAuthorizedUserRedirectPath())
            End If



            '#########################################################################
            'RIGHT NOW ONLY SITE ADMINS SHOULD BE USING THIS PAGE SO ALLOW ONLY THEM
            '#########################################################################
            Select Case True
                Case Me.IsInRole("ContentAdmin")
                    '#####################################
                    'CONTINUE ON AND GIVE ACCESS TO PAGE
                    '#####################################
                Case Else
                    Response.Redirect(Me.UnAuthorizedUserRedirectPath())
            End Select


            If Not IsPostBack Then
                Call dataLoad()

                If ListBox1.SelectedIndex < 0 Then
                    ListBox1.DataSource = WebCrawledPageCollection.Keys
                    ListBox1.DataBind()
                    ListBox1.SelectedIndex = 0
                Else
                    '#################################
                    'USER HAS ALREADY SELECTED VALUE
                    '#################################

                End If

                Call loadForm()

            End If

            btnAddNewPage.Enabled = False
            btnCancelAddNewPage.Enabled = False

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private ReadOnly Property UnAuthorizedUserRedirectPath() As String
        Get
            Select Case Environment.MachineName.ToLower
                Case "kstlmcc2p01"
                    '#######
                    'PROD WEB
                    '#######
                    Return "http://www.Charter.com/Visitors/Home.aspx"
                Case "kstlmcc2p02"
                    '#######
                    'PROD WEB 
                    '#######
                    Return "http://www.Charter.com/Visitors/Home.aspx"
                Case "kstlmweb66"
                    '#######
                    'UAT WEB 
                    '#######
                    Return "http://cc2uatx.chartercom.com/Visitors/Home.aspx"
                Case "kstlmweb67"
                    '#######
                    'UAT WEB 
                    '#######
                    Return "http://cc2uatx.chartercom.com/Visitors/Home.aspx"
                Case "kstlmcc2p03"
                    '#######
                    'PROD APP 
                    '#######
                    Return "http://cc2prda"
                Case "kstlmcc2p04"
                    '#######
                    'PROD APP 
                    '#######
                    Return "http://cc2prda"
                Case "kstlmweb68"
                    '#######
                    'UAT APP 
                    '#######
                    Return "http://cc2uata"
                Case "kstlmweb69"
                    '#######
                    'UAT APP
                    '#######
                    Return "http://cc2uata"
                Case "kstlmweb65"
                    '#######
                    'DEV WEB AND APP
                    '#######
                    Return "http://KSTLMWEB65:8080"
                Case "kstlintcncegenm"
                    '#######
                    'DEV WEB AND APP
                    '#######
                    Return "http://localhost/bl.remotinghost/login.aspx"
                Case Else
                    '#####################################
                    'THIS SHOULD ONLY BE LOCALHOST STUFF HERE.
                    '#####################################
                    Return "http://www.Charter.com/Visitors/Home.aspx"
            End Select
        End Get
    End Property

    Private Property DB() As Database
        Get
            Return _db
        End Get
        Set(ByVal value As Database)
            _db = value
        End Set
    End Property
    Private Property CMD() As DbCommand
        Get
            Return _cmd
        End Get
        Set(ByVal value As DbCommand)
            _cmd = value
        End Set
    End Property

    Sub dataLoad()
        Dim strSQL As String = "SELECT * FROM [Admin].[PAGE_MANAGEMENT] ORDER BY PAGE_URL, HBX_PAGE_CATEGORY, HBX_PAGE_NAME"
        Me.CMD = Me.DB.GetSqlStringCommand(strSQL)
        Dim DS As DataSet = DB.ExecuteDataSet(Me.CMD)

        If Not (DS Is Nothing) Then
            If DS.Tables.Count() > 0 Then

                '#############################################
                '#############################################

                For Each row As Data.DataRow In DS.Tables(0).Rows
                    Dim lRecord As New WebCrawledPage
                    If Not (row.Item("ID") Is System.DBNull.Value) Then
                        If Not (row.Item("ID") Is Nothing) Then
                            lRecord.DBTableID = CType(row.Item("ID"), Integer)
                        End If
                    End If
                    If Not (row.Item("KEYWORDS") Is System.DBNull.Value) Then
                        If Not (row.Item("KEYWORDS") Is Nothing) Then
                            lRecord.PageKeywords = CType(row.Item("KEYWORDS").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("HBX_PAGE_NAME") Is System.DBNull.Value) Then
                        If Not (row.Item("HBX_PAGE_NAME") Is Nothing) Then
                            lRecord.HBXPageName = CType(row.Item("HBX_PAGE_NAME").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("HBX_PAGE_CATEGORY") Is System.DBNull.Value) Then
                        If Not (row.Item("HBX_PAGE_CATEGORY") Is Nothing) Then
                            lRecord.HBXPageCategory = CType(row.Item("HBX_PAGE_CATEGORY").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("PAGE_DESCRIPTION") Is System.DBNull.Value) Then
                        If Not (row.Item("PAGE_DESCRIPTION") Is Nothing) Then
                            lRecord.PageDescription = CType(row.Item("PAGE_DESCRIPTION").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("PAGE_STYLESHEET_URL") Is System.DBNull.Value) Then
                        If Not (row.Item("PAGE_STYLESHEET_URL") Is Nothing) Then
                            lRecord.StyleSheetURL = CType(row.Item("PAGE_STYLESHEET_URL").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("PAGE_SEARCH_TEXT") Is System.DBNull.Value) Then
                        If Not (row.Item("PAGE_SEARCH_TEXT") Is Nothing) Then
                            lRecord.searchWords = CType(row.Item("PAGE_SEARCH_TEXT").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("PAGE_SEARCH_RANKING") Is System.DBNull.Value) Then
                        If Not (row.Item("PAGE_SEARCH_RANKING") Is Nothing) Then
                            lRecord.SearchRanking = CType(row.Item("PAGE_SEARCH_RANKING"), Integer)
                        End If
                    End If
                    If Not (row.Item("CREATE_DATE") Is System.DBNull.Value) Then
                        If Not (row.Item("CREATE_DATE") Is Nothing) Then
                            lRecord.CreateDate = CType(row.Item("CREATE_DATE"), Date)
                        End If
                    End If
                    If Not (row.Item("MODIFY_DATE") Is System.DBNull.Value) Then
                        If Not (row.Item("MODIFY_DATE") Is Nothing) Then
                            lRecord.ModifiedDate = CType(row.Item("MODIFY_DATE"), Date)
                        End If
                    End If
                    If Not (row.Item("PAGE_URL") Is System.DBNull.Value) Then
                        If Not (row.Item("PAGE_URL") Is Nothing) Then
                            lRecord.pageURL = CType(row.Item("PAGE_URL").ToString().Trim(), String)
                        End If
                    End If
                    If Not (row.Item("TITLE") Is System.DBNull.Value) Then
                        If Not (row.Item("TITLE") Is Nothing) Then
                            lRecord.Title = CType(row.Item("TITLE").ToString().Trim(), String)
                        End If
                    End If

                    If Not WebCrawledPageCollection.ContainsKey(lRecord.pageURL) Then
                        WebCrawledPageCollection.Add(lRecord.pageURL, lRecord)
                    End If
                Next

                '#############################################
                '#############################################

                'ViewState("WebCrawledPageCollection") = WebCrawledPageCollection


                '########################################################################################
                'THE USE OF THE SESSION OBJECT WAS DONE AFTER THE FACT.  THIS WASN'T THE PREFERED 
                'METHOD OF PERSISTANCE BECAUSE THE APPLICATION SERVERS DONT USE THE STICKY SESSIONS.
                'NO STICKY SESSIONS MEANS YOU DONT KNOW WHAT SERVER YOU'LL END UP ON, USING SESSION 
                'OBJECT WOULDN'T BE DEPENDABLE IT BEING THERE.
                'USING THE VIEWSTATE TO HOLD THE COLLECTION WAS RECOMMENDED.  THIS APPROACH WOULD BE 
                'FINE IF IT WASN'T FOR THE LARGE AMOUNT OF TEXT IN THE "PAGE SEARCH TEXT" FIELD BEING 
                'NEEDED AS PART OF THE COLLECTION AND STORING THE WHOLE COLLECTION IN VIEWSTATE. 
                'FOR PERFORMANCE REASONS, WE'LL USE THE SESSION OBJECT FOR NOW AND WHEN THE SESSION 
                'OBJECT IS NOTHING THEN WE'LL JUST MAKE ANOTHER CALL OUT TO GET IT AGAIN.  NOT A BIG 
                'DEAL FOR LESS THAN 5 USERS AT A TIME.
                '########################################################################################
                Session("WebCrawledPageCollection") = WebCrawledPageCollection

            Else
                Throw New Exception("no tables returned from the page management table query")
            End If
        Else
            Throw New Exception("no value returned from the page management table")
        End If

    End Sub

    Sub loadForm()
        '########################################################################################
        'THE USE OF THE SESSION OBJECT WAS DONE AFTER THE FACT.  THIS WASN'T THE PREFERED 
        'METHOD OF PERSISTANCE BECAUSE THE APPLICATION SERVERS DONT USE THE STICKY SESSIONS.
        'NO STICKY SESSIONS MEANS YOU DONT KNOW WHAT SERVER YOU'LL END UP ON, USING SESSION 
        'OBJECT WOULDN'T BE DEPENDABLE IT BEING THERE.
        'USING THE VIEWSTATE TO HOLD THE COLLECTION WAS RECOMMENDED.  THIS APPROACH WOULD BE 
        'FINE IF IT WASN'T FOR THE LARGE AMOUNT OF TEXT IN THE "PAGE SEARCH TEXT" FIELD BEING 
        'NEEDED AS PART OF THE COLLECTION AND STORING THE WHOLE COLLECTION IN VIEWSTATE. 
        'FOR PERFORMANCE REASONS, WE'LL USE THE SESSION OBJECT FOR NOW AND WHEN THE SESSION 
        'OBJECT IS NOTHING THEN WE'LL JUST MAKE ANOTHER CALL OUT TO GET IT AGAIN.  NOT A BIG 
        'DEAL FOR LESS THAN 5 USERS AT A TIME.
        '########################################################################################
        If (Session("WebCrawledPageCollection") Is Nothing) Then
            '############################
            'LOAD SESSION FROM DB CALL 
            '############################
            Call dataLoad()
        End If


        If Not (Session("WebCrawledPageCollection") Is Nothing) Then
            WebCrawledPageCollection = Session("WebCrawledPageCollection")

            If WebCrawledPageCollection.ContainsKey(ListBox1.SelectedValue) Then
                Dim lRecord As WebCrawledPage = WebCrawledPageCollection(ListBox1.SelectedValue)

                If Not (lRecord Is Nothing) Then
                    lblTableID.Text = lRecord.DBTableID
                    txtTitle.Text = lRecord.Title
                    txtKeywords.Text = lRecord.PageKeywords
                    txtHBXPageName.Text = lRecord.HBXPageName
                    txtHBXPageCategory.Text = lRecord.HBXPageCategory
                    txtPageDescription.Text = lRecord.PageDescription
                    txtPageSearchText.Text = lRecord.searchWords
                    txtPageSearchRanking.Text = lRecord.SearchRanking
                    txtPageStyleSheetURL.Text = lRecord.StyleSheetURL
                    If (lRecord.CreateDate = Nothing) Then
                        lblCreateDate.Text = ""
                    Else
                        lblCreateDate.Text = lRecord.CreateDate
                    End If
                    lblModifyDate.Text = lRecord.ModifiedDate
                    txtPageURL.Text = lRecord.pageURL
                    txtPageURL.Columns = lRecord.pageURL.Length()
                End If

            End If
        Else
            '############################
            'LOAD SESSION FROM DB CALL 
            '############################
            Call dataLoad()
        End If




        'If Not (ViewState("WebCrawledPageCollection") Is Nothing) Then
        '    WebCrawledPageCollection = ViewState("WebCrawledPageCollection")

        '    If WebCrawledPageCollection.ContainsKey(ListBox1.SelectedValue) Then
        '        Dim lRecord As WebCrawledPage = WebCrawledPageCollection(ListBox1.SelectedValue)

        '        If Not (lRecord Is Nothing) Then
        '            lblTableID.Text = lRecord.DBTableID
        '            txtTitle.Text = lRecord.Title
        '            txtKeywords.Text = lRecord.PageKeywords
        '            txtHBXPageName.Text = lRecord.HBXPageName
        '            txtHBXPageCategory.Text = lRecord.HBXPageCategory
        '            txtPageDescription.Text = lRecord.PageDescription
        '            txtPageSearchText.Text = lRecord.searchWords
        '            txtPageSearchRanking.Text = lRecord.SearchRanking
        '            txtPageStyleSheetURL.Text = lRecord.StyleSheetURL
        '            lblCreateDate.Text = lRecord.CreateDate
        '            lblModifyDate.Text = lRecord.ModifiedDate
        '            txtPageURL.Text = lRecord.pageURL
        '            txtPageURL.Columns = lRecord.pageURL.Length()
        '        End If

        '    End If

        'Else
        '    Throw New Exception("WebCrawledPageCollection is not set to object")
        'End If

    End Sub
    Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Call loadForm()

    End Sub

    Private Function Add_Update_Page() As Integer
        Dim returnCode As Integer
        Try

            CMD = DB.GetStoredProcCommand("[Admin].[ADD_OR_UPDATE_PAGE_MANAGEMENT]")

            If txtTitle.Text <> Nothing And txtTitle.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@TITLE", DbType.String, txtTitle.Text.Trim())
            End If
            If txtKeywords.Text <> Nothing And txtKeywords.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@KEYWORDS", DbType.String, txtKeywords.Text.Trim())
            End If
            If txtHBXPageName.Text <> Nothing And txtHBXPageName.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@HBX_PAGE_NAME", DbType.String, txtHBXPageName.Text.Trim())
            End If
            If txtHBXPageCategory.Text <> Nothing And txtHBXPageCategory.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@HBX_PAGE_CATEGORY", DbType.String, txtHBXPageCategory.Text.Trim())
            End If
            If txtPageDescription.Text <> Nothing And txtPageDescription.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@PAGE_DESCRIPTION", DbType.String, txtPageDescription.Text.Trim())
            End If
            If txtPageStyleSheetURL.Text <> Nothing And txtPageStyleSheetURL.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@PAGE_STYLESHEET_URL", DbType.String, txtPageStyleSheetURL.Text.Trim().ToLower())
            End If
            If txtPageSearchText.Text <> Nothing And txtPageSearchText.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@PAGE_SEARCH_TEXT", DbType.String, txtPageSearchText.Text.Trim())
            End If
            If txtPageSearchRanking.Text <> Nothing And txtPageSearchRanking.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@PAGE_SEARCH_RANKING", DbType.Int32, txtPageSearchRanking.Text.Trim())
            End If
            If txtPageURL.Text <> Nothing And txtPageURL.Text.Trim() <> "" Then
                DB.AddInParameter(CMD, "@PAGE_URL", DbType.String, txtPageURL.Text.Trim().ToLower())
            End If


            returnCode = DB.ExecuteScalar(CMD)

            Return returnCode

        Catch ex As Exception
            Throw ex
        Finally
            If Not CMD Is Nothing Then
                CMD.Dispose()
            End If
        End Try
    End Function
    Protected Sub btnUpdatePage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdatePage.Click
        Dim returnCode As Integer = Add_Update_Page()

        If returnCode <> 0 Then
            '###########################
            'SOMETHING BAD HAS HAPPENED.
            '###########################
        Else
            '#################
            'GOOD RESPONSE
            '#################
            Response.Redirect("PageManagement.aspx")
        End If
    End Sub

    Protected Sub btnDeletePage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeletePage.Click

        Dim retCode As Integer
        Try
            Dim urlToDelete As String = ListBox1.SelectedValue.Trim()

            If urlToDelete.Trim() <> "" Then
                CMD = DB.GetStoredProcCommand("[Admin].[DELETE_PAGE_FROM_PAGE_MANAGEMENT]")

                DB.AddInParameter(CMD, "@PAGE_URL", DbType.String, urlToDelete)

                retCode = DB.ExecuteScalar(CMD)
            Else
                Throw New Exception("No value selected in the URL list box, this is needed to delete a URL")
            End If

            Response.Redirect("PageManagement.aspx")

        Catch ex As Exception
            Throw ex
        Finally
            If Not CMD Is Nothing Then
                CMD.Dispose()
            End If
        End Try

    End Sub

    Protected Sub btnCreateNewPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateNewPage.Click
        '###################################
        'HIDE BUTTONS THAT ARE NOT NEEDED.
        '###################################
        btnCreateNewPage.Enabled = False
        btnDeletePage.Enabled = False
        btnUpdatePage.Enabled = False

        '###################################
        'CLEAR THE WEBFORM
        '###################################
        txtHBXPageCategory.Text = "/your_values/your_values/your_values/"
        txtHBXPageName.Text = "***NEW PAGE TO ADD TO HBX ***"
        txtKeywords.Text = "your value,your value,your value"
        txtPageDescription.Text = ""
        txtPageSearchRanking.Text = ""
        txtPageSearchText.Text = "this value will allow the page to show up in search results..."
        txtPageStyleSheetURL.Text = "../styles/charter.css"
        txtPageURL.Text = "your_folder/your_page_name.aspx?test=" & System.Guid.NewGuid().ToString().Substring(0, 20)
        txtTitle.Text = "Charter Communications -"
        lblCreateDate.Text = ""
        lblModifyDate.Text = ""
        lblTableID.Text = ""

        '####################
        'DISABLE THE LISTBOX
        '####################
        ListBox1.Enabled = False

        '###################
        'APPLY FORMATTING
        '###################
        txtPageURL.Columns = txtPageURL.Text.Length()


        '#######################
        'ENABLE THE ADD BUTTON
        '#######################
        btnAddNewPage.Enabled = True
        btnCancelAddNewPage.Enabled = True


        txtTitle.Focus()

    End Sub

    Protected Sub btnAddNewPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNewPage.Click
        Dim returnCode As Integer = Add_Update_Page()

        If returnCode <> 0 Then
            '###########################
            'SOMETHING BAD HAS HAPPENED.
            '###########################
        Else
            '#################
            'GOOD RESPONSE
            '#################
            Response.Redirect("PageManagement.aspx")
        End If
    End Sub



    Protected Sub btnCancelAddNewPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelAddNewPage.Click
        '###############
        'RESET PAGE
        '###############
        Response.Redirect("PageManagement.aspx")
    End Sub
End Class
