Imports System
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections.Generic

Partial Class Admin
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            pnlNewUser.Visible = False
            fldChangePassword.Visible = False
            Dim ds As New DataSet()
            Dim dsRole As New DataSet()
            '**********************  DONT NEED IT    *******************
            'Dim myconn As SqlConnection = New SqlConnection()
            'Dim ds As DataSet = New DataSet()
            'myconn.ConnectionString = "server=KSTLMSQL59;database=CharterDotCom_CMS;user=charterdotcomdbo;password=charter!;trusted_connection=false"
            'myconn.Open()

            'Dim mycommand As SqlCommand = New SqlCommand("select userid,username from [content.NewUsers]", myconn)
            'Dim myadpt As SqlDataAdapter = New SqlDataAdapter(mycommand)
            'myadpt.Fill(ds)
            '**************************************************************
            Dim CMS As New CMS.CMSService()
            CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
            ds = CMS.GetUsers()


            dsRole = CMS.GetContentAuthoringRoles()
            ddlRoleName.DataSource = dsRole
            ddlRoleName.DataValueField = dsRole.Tables(0).Columns(0).ToString()
            ddlRoleName.DataTextField = dsRole.Tables(0).Columns(1).ToString()
            ddlRoleName.DataBind()

            PopulateDropdownList(ds)

        End If
        btnUserStatus.Visible = False
    End Sub

    Protected Sub ddlUserName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlUserName.SelectedIndexChanged

        lblErrorMsg.Visible = False
        'btnChangePassword.Visible = True
        fldChangePassword.Visible = False

        If (ddlUserName.SelectedItem.ToString() = "Select a user") Then

            dg1.Visible = False
            btnSave.Visible = False
            pnlNewUser.Visible = False
            btnChangePassword.Visible = False
            btnUserStatus.Visible = False
        ElseIf (ddlUserName.SelectedItem.ToString() = "Create a new user..") Then
            btnChangePassword.Visible = False
            pnlNewUser.Visible = True
            dg1.Visible = True
            Dim ds As DataSet = New DataSet()
            Dim CMS As New CMS.CMSService()
            CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
            ds = CMS.GetTemplates()
            Dim dt As DataTable = New DataTable("templatetable")
            Dim colTemplateName As DataColumn = New DataColumn("template")
            colTemplateName.DataType = System.Type.GetType("System.String")
            Dim colTemplateID As DataColumn = New DataColumn("templateid")
            colTemplateID.DataType = System.Type.GetType("System.Int32")


            dt.Columns.Add(colTemplateName)
            dt.Columns.Add(colTemplateID)

            Dim drnew As DataRow
            For Each dr As DataRow In ds.Tables(0).Rows
                drnew = dt.NewRow()
                drnew("template") = dr("TemplateName")
                drnew("templateid") = dr("TemplateID")
                dt.Rows.Add(drnew)
            Next


            dg1.DataSource = dt
            dg1.DataBind()
            btnSave.Visible = True

            btnUserStatus.Visible = False
        Else

            dg1.Visible = True
            btnSave.Visible = True
            pnlNewUser.Visible = False

            Dim myuserid As Integer
            myuserid = CType(ddlUserName.SelectedValue.ToString(), Integer)

            Dim myroleid As Integer
            myroleid = CType(ddlRoleName.SelectedValue.ToString(), Integer)

            Dim ds As DataSet = New DataSet()
            Dim ds1 As DataSet = New DataSet()

            Dim CMS As New CMS.CMSService()
            CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
            ds = CMS.GetTemplates()

            Dim dt As DataTable = New DataTable("templatetable")
            Dim colTemplateName As DataColumn = New DataColumn("template")
            colTemplateName.DataType = System.Type.GetType("System.String")
            Dim colTemplateID As DataColumn = New DataColumn("templateid")
            colTemplateID.DataType = System.Type.GetType("System.Int32")


            dt.Columns.Add(colTemplateName)
            dt.Columns.Add(colTemplateID)

            Dim drnew As DataRow
            For Each dr As DataRow In ds.Tables(0).Rows
                drnew = dt.NewRow()
                drnew("template") = dr("TemplateName")
                drnew("templateid") = dr("TemplateID")
                dt.Rows.Add(drnew)
            Next

            dg1.DataSource = dt
            dg1.DataBind()

            ds1 = CMS.GetTemplatesForUser(myuserid, myroleid)

            Dim templatename As String
            Dim rowcount As Integer = 0
            For Each dr As DataRow In ds1.Tables(0).Rows


                templatename = CType(dr("templatename"), String)
                For Each dr1 As DataRow In ds.Tables(0).Rows
                    If (templatename = dr1("templatename")) Then
                        Exit For
                    End If
                    rowcount = rowcount + 1
                Next

                CType(dg1.Items(rowcount).FindControl("chk"), CheckBox).Checked = True
                rowcount = 0
            Next
            If InStr(ddlUserName.SelectedItem.ToString(), "- Disabled") > 0 Then
                btnUserStatus.Text = "Enable"
            Else
                btnUserStatus.Text = "Disable"
            End If
            'btnUserStatus.Visible = True
        End If

    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Dim username As String = txtUserName.Text.ToString()
        Dim firstname As String = txtFirstName.Text.ToString()
        Dim lastname As String = txtLastName.Text.ToString()
        Dim selectedItem As String = ddlUserName.SelectedItem.Text.ToString()

        Dim i As Integer
        Dim selectedCheckBox As New List(Of String)
        Dim templateid As Integer

        Dim isCreateNewSelected As Boolean = False
        Dim isTemplateSelected As Boolean = False

        Dim email As String = txtEmail.Text.ToString() & "@chartercom.com"

        isCreateNewSelected = IsCreateNewUserSelected()

        Dim _count As Integer = 0
        Dim _password As String = txtPassword.Text.ToString()
        If isCreateNewSelected Then
            Dim regularEx1 As Regex = New Regex("^.*(?=.{8,})(?=.*\d).*$")
            Dim regularEx2 As Regex = New Regex("^.*(?=.{8,})(?=.*[a-z]).*$")
            Dim regularEx3 As Regex = New Regex("^.*(?=.{8,})(?=.*[A-Z]).*$")
            Dim regularEx4 As Regex = New Regex("^.*(?=.{8,})(?=.*[!$#%]).*$")

            'Dim regularExForEmail As Regex = New Regex("^((((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$).((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$))|(((?=.*[a-z])(?=.*[A-Z]).*$).((?=.*[a-z])(?=.*[A-Z]).*$)))")
            'Dim _emailValid As Boolean = regularExForEmail.Match(email).Success


            Dim match As Boolean = regularEx1.Match(_password).Success

            If regularEx1.Match(_password).Success Then
                _count = _count + 1
            End If
            If regularEx2.Match(_password).Success Then
                _count = _count + 1
            End If

            If regularEx3.Match(_password).Success Then
                _count = _count + 1
            End If
            If regularEx4.Match(_password).Success Then
                _count = _count + 1
            End If
        Else
            _count = 4
        End If


        If (_count >= 3) Then

            For i = 0 To dg1.Items.Count - 1
                If (CType(dg1.Items(i).FindControl("chk"), CheckBox).Checked = True) Then
                    templateid = CType(dg1.Items(i).Cells(2).Text, Integer)
                    selectedCheckBox.Add(templateid)
                    isTemplateSelected = True
                End If

            Next
            If isCreateNewSelected And (Not isTemplateSelected) Then
                selectedCheckBox.Add(0)
            End If
            If isTemplateSelected Or (Not isCreateNewSelected) Then
                lblErrorMsg.Visible = False

                If Not isCreateNewSelected Then
                    Dim myuserid As Integer = CType(ddlUserName.SelectedValue.ToString(), Integer)
                    Dim myroleid As Integer = CType(ddlRoleName.SelectedValue.ToString(), Integer)

                    Dim CMS As New CMS.CMSService()
                    CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
                    CMS.saveSelectedTemplate(myuserid, myroleid, selectedCheckBox.ToArray)

                Else
                    Dim isNewUserCreated As Boolean
                    Dim CMS As New CMS.CMSService()
                    CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials

                    '***********  CHECKING IF THE USER ENTERED ALREADY EXISTS *********************
                    Dim intId As Integer = 0
                    Dim isDuplicateUser As Boolean
                    intId = CMS.GetUserID(Replace(username.ToLower(), "chtr\", ""))
                    If intId = 0 Then
                        isDuplicateUser = False
                    Else
                        isDuplicateUser = True
                    End If
                    '******************************************************************************
                    If Not isDuplicateUser Then
                        isNewUserCreated = CMS.createNewUser(Replace(username.ToLower(), "chtr\", ""), _password, firstname, lastname, email, Replace(Me.User.Identity.Name, "CHTR\", ""))
                        If (isNewUserCreated) Then
                            Dim isTemplateSaved As Boolean
                            Dim myUserID, myroleid As Integer
                            myUserID = CMS.GetUserID(Replace(username.ToLower(), "chtr\", ""))
                            myroleid = CType(ddlRoleName.SelectedValue.ToString(), Integer)

                            isTemplateSaved = CMS.saveSelectedTemplate(myUserID, myroleid, selectedCheckBox.ToArray)

                            If (Not isTemplateSaved) Then
                                Throw New Exception("Failed to save")
                            Else
                                Dim ds1 As New DataSet()
                                ds1 = CMS.GetUsers()
                                PopulateDropdownList(ds1)
                                txtUserName.Text = ""
                                txtFirstName.Text = ""
                                txtLastName.Text = ""
                                ddlUserName.Items.FindByValue(myUserID.ToString()).Selected = True
                                ddlUserName_SelectedIndexChanged(Nothing, Nothing)
                            End If
                        Else
                            Throw New Exception("Failed to save")
                        End If
                    Else
                        Response.Write("This User already exists. Please enter another user.")
                    End If
                End If
            Else
                lblErrorMsg.Visible = True
            End If
        Else
            lblErrorMsg.Visible = True
            lblErrorMsg.Text = "Password is Not Valid"
        End If
    End Sub

    Private Function IsCreateNewUserSelected() As Boolean
        Dim selectedItem As String = ddlUserName.SelectedItem.Text.ToString()
        If (selectedItem = "Create a new user..") Then
            Return True
        Else
            Return False
        End If

    End Function

    Protected Sub ddlRoleName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlRoleName.SelectedIndexChanged
        Try

            lblErrorMsg.Visible = False
            If (ddlUserName.SelectedItem.ToString() = "Select a user") Then

                dg1.Visible = False
                btnSave.Visible = False
                pnlNewUser.Visible = False
            ElseIf (ddlUserName.SelectedItem.ToString() = "Create a new user..") Then
                pnlNewUser.Visible = True
                dg1.Visible = True
                Dim ds As DataSet = New DataSet()
                '********************** DONT NEED IT **********************************************
                'Dim myconn As SqlConnection = New SqlConnection()
                'Dim ds As DataSet = New DataSet()
                'myconn.ConnectionString = "server=KSTLMSQL59;database=CharterDotCom_CMS;user=charterdotcomdbo;password=charter!;trusted_connection=false"
                'myconn.Open()
                'Dim query As String
                'query = "select TemplateName from content.Template"
                'Dim mycommand As SqlCommand = New SqlCommand(query, myconn)
                'Dim myadpt As SqlDataAdapter = New SqlDataAdapter(mycommand)
                'myadpt.Fill(ds)
                '**********************************************************************************
                Dim CMS As New CMS.CMSService()
                CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
                ds = CMS.GetTemplates()

                'Dim dt As DataTable = New DataTable("templatetable")
                'Dim colTemplateName As DataColumn = New DataColumn("template")
                'colTemplateName.DataType = System.Type.GetType("System.String")
                'dt.Columns.Add(colTemplateName)
                'Dim drnew As DataRow
                'For Each dr As DataRow In ds.Tables(0).Rows
                '	drnew = dt.NewRow()
                '	drnew("template") = dr("TemplateName")
                '	dt.Rows.Add(drnew)
                'Next

                Dim dt As DataTable = New DataTable("templatetable")
                Dim colTemplateName As DataColumn = New DataColumn("template")
                colTemplateName.DataType = System.Type.GetType("System.String")
                Dim colTemplateID As DataColumn = New DataColumn("templateid")
                colTemplateID.DataType = System.Type.GetType("System.Int32")


                dt.Columns.Add(colTemplateName)
                dt.Columns.Add(colTemplateID)

                Dim drnew As DataRow
                For Each dr As DataRow In ds.Tables(0).Rows
                    drnew = dt.NewRow()
                    drnew("template") = dr("TemplateName")
                    drnew("templateid") = dr("TemplateID")
                    dt.Rows.Add(drnew)
                Next


                dg1.DataSource = dt
                dg1.DataBind()

                'dg1.DataSource = ds
                'dg1.DataBind()

                btnSave.Visible = True


            Else

                dg1.Visible = True
                btnSave.Visible = True
                pnlNewUser.Visible = False

                Dim myuserid As Integer
                myuserid = CType(ddlUserName.SelectedValue.ToString(), Integer)

                Dim myroleid As Integer
                myroleid = CType(ddlRoleName.SelectedValue.ToString(), Integer)

                Dim ds As DataSet = New DataSet()
                Dim ds1 As DataSet = New DataSet()

                '******************  DONT NEED IT **********************************
                'Dim myconn As SqlConnection = New SqlConnection()
                'myconn.ConnectionString = "server=KSTLMSQL59;database=CharterDotCom_CMS;user=charterdotcomdbo;password=charter!;trusted_connection=false"
                'myconn.Open()
                '********************************************************************************


                '*************************      DONT NEED IT     **************************
                'Dim query As String
                'query = "select TemplateName from content.Template"
                'Dim mycommand As SqlCommand = New SqlCommand(query, myconn)
                'Dim myadpt As SqlDataAdapter = New SqlDataAdapter(mycommand)
                'myadpt.Fill(ds)
                '******************************************************************************

                '************************** DONT NEED IT ********************
                'Dim query1 As String = "select cn.templateid,templatename from [content.newtemplate_users] cn inner join content.template ct on cn.templateid=ct.templateid  where userid='" & myuserid & "'"
                'Dim mycommand1 As SqlCommand = New SqlCommand(query1, myconn)
                'Dim myadpt1 As SqlDataAdapter = New SqlDataAdapter(mycommand1)
                'myadpt1.Fill(ds1)
                '******************************************************************************

                Dim CMS As New CMS.CMSService()
                CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
                ds = CMS.GetTemplates()

                Dim dt As DataTable = New DataTable("templatetable")
                Dim colTemplateName As DataColumn = New DataColumn("template")
                colTemplateName.DataType = System.Type.GetType("System.String")
                Dim colTemplateID As DataColumn = New DataColumn("templateid")
                colTemplateID.DataType = System.Type.GetType("System.Int32")


                dt.Columns.Add(colTemplateName)
                dt.Columns.Add(colTemplateID)

                Dim drnew As DataRow
                For Each dr As DataRow In ds.Tables(0).Rows
                    drnew = dt.NewRow()
                    drnew("template") = dr("TemplateName")
                    drnew("templateid") = dr("TemplateID")
                    dt.Rows.Add(drnew)
                Next

                dg1.DataSource = dt
                dg1.DataBind()

                ds1 = CMS.GetTemplatesForUser(myuserid, myroleid)

                'Dim templateid As Integer
                Dim templatename As String
                Dim rowcount As Integer = 0
                For Each dr As DataRow In ds1.Tables(0).Rows


                    'templateid = CType(dr("templateid"), Integer)
                    templatename = CType(dr("templatename"), String)
                    For Each dr1 As DataRow In ds.Tables(0).Rows
                        If (templatename = dr1("templatename")) Then
                            Exit For
                        End If
                        rowcount = rowcount + 1
                    Next

                    CType(dg1.Items(rowcount).FindControl("chk"), CheckBox).Checked = True
                    rowcount = 0
                Next

            End If

        Catch ex As Exception

        End Try
    End Sub

    Public Sub PopulateDropdownList(ByVal ds As DataSet)

        ddlUserName.DataSource = ds
        Dim rowcount As Integer = ds.Tables(0).Rows.Count

        ddlUserName.DataValueField = ds.Tables(0).Columns(0).ToString()
        ddlUserName.DataTextField = ds.Tables(0).Columns(1).ToString()
        ddlUserName.DataBind()
        ddlUserName.Items.Insert(0, "Select a user")
        If Me.User.IsInRole(ConfigurationManager.AppSettings("UserAdminRoleName")) Then
            ddlUserName.Items.Insert(rowcount + 1, "Create a new user..")
        Else
            Dim objItem As ListItem = ddlRoleName.Items.FindByText("UserAdmin")
            If objItem IsNot Nothing Then
                ddlRoleName.Items.Remove(objItem)
            End If
        End If

    End Sub

    


    Protected Sub btnChangePassword_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnChangePassword.Click
        fldChangePassword.Visible = True
        lblError.Visible = False
        Dim ds As DataSet

        Dim _userid As Integer = CType(ddlUserName.SelectedValue.ToString(), Integer)
        Dim CMS As New CMS.CMSService()
        CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
        ds = CMS.GetUserName(_userid)

        txtUser.Text = ds.Tables(0).Rows(0)(0).ToString()

    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        Dim _passwordUpdated As Boolean
        Dim _count As Integer = 0

        Dim regularEx1 As Regex = New Regex("^.*(?=.{8,})(?=.*\d).*$")
        Dim regularEx2 As Regex = New Regex("^.*(?=.{8,})(?=.*[a-z]).*$")
        Dim regularEx3 As Regex = New Regex("^.*(?=.{8,})(?=.*[A-Z]).*$")
        Dim regularEx4 As Regex = New Regex("^.*(?=.{8,})(?=.*[!$#%]).*$")
        Dim _userid As Integer = CType(ddlUserName.SelectedValue.ToString(), Integer)
        Dim _password As String = txtNewPassword.Text.ToString()
        Dim match As Boolean = regularEx1.Match(_password).Success

        If regularEx1.Match(_password).Success Then
            _count = _count + 1
        End If
        If regularEx2.Match(_password).Success Then
            _count = _count + 1
        End If

        If regularEx3.Match(_password).Success Then
            _count = _count + 1
        End If
        If regularEx4.Match(_password).Success Then
            _count = _count + 1
        End If

        If (_count >= 3) Then

            Dim CMS As New CMS.CMSService()
            CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
            _passwordUpdated = CMS.UpdatePassword(_userid, _password)
            lblError.Visible = True
            If (_passwordUpdated) Then
                lblError.Text = "Password is successfully Updated"
            Else
                lblError.Text = "Password is not updated"
            End If
        Else
            lblError.Visible = True
            lblError.Text = "Password is not valid"

        End If
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        fldChangePassword.Visible = False
    End Sub

    Protected Sub btnUserStatus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUserStatus.Click
        Try
            Dim CMS As New CMS.CMSService()
            CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials

            If btnUserStatus.Text.ToLower().Trim() = "enable" Then
                CMS.EnableUser(CInt(ddlUserName.SelectedValue.ToString()))
            Else
                CMS.DisableUser(CInt(ddlUserName.SelectedValue.ToString()))
            End If
        Catch ex As Exception

        End Try
    End Sub
End Class
