Imports System.Collections.Generic
Imports System.Net.Mail

Partial Class Configurations_Controls_UserDetails
    Inherits System.Web.UI.UserControl

    Public Event newUserCreated As GenericDelegate


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


        If Me.IsPostBack Then


             If Not Me.ViewState("userid") Is Nothing Then
                'edit user flow
                 BuildRoleTable(Int32.Parse(Me.ViewState("userid")))
                 Me.txtPassword.Visible = False
                 Me.chkResetPassword.Visible = True
             Else
                Me.chkResetPassword.Visible = False
                Me.txtPassword.Visible = True
             End If

        End If

         lblErrorMessage.Visible = False
         Me.txtUserName.ReadOnly = True
       
        
    End Sub

    Sub BuildRoleTable(ByVal userid As Int32)
        tblRoles.Rows.Clear()
        'get user's roles
        Dim userrolesTA As DALTableAdapters.GetUserRolesByIDTableAdapter = New DALTableAdapters.GetUserRolesByIDTableAdapter
        Dim userroles As DAL.GetUserRolesByIDDataTable = userrolesTA.GetDataByID(userid)


        'set role state
        Dim rolesTA As DALTableAdapters.RoleTableAdapter = New DALTableAdapters.RoleTableAdapter
        Dim roles As DAL.RoleDataTable = rolesTA.GetSystemRoles()
        For Each role As DAL.RoleRow In roles
            Dim tblrow As TableRow = New TableRow
            tblrow.HorizontalAlign = HorizontalAlign.Left
            Dim tblcell As TableCell = New TableCell
            Dim chkRole As CheckBox = New CheckBox
            chkRole.AutoPostBack = True
            AddHandler chkRole.CheckedChanged, AddressOf Me.EditUserRoleChecked
            chkRole.Text = role.RoleName
            If Not userroles.FindByRoleID(role.RoleID) Is Nothing Then
                chkRole.Checked = True
            End If
            chkRole.Attributes.Add("roleid", role.RoleID)
            tblcell.Controls.Add(chkRole)
            tblrow.Cells.Add(tblcell)
            tblRoles.Rows.Add(tblrow)
        Next

        'save the state of the table to the session variable
        Session("temproletable") = tblRoles
    End Sub


    
    Public Sub SetEditUser(ByVal userid As Int32)

        Me.txtPassword.Visible = False
        Me.chkResetPassword.Visible = True

        'add to view state
        Me.ViewState.Add("userid", userid)

        'load data
        Dim usersTA As DALTableAdapters.UsersTableAdapter = New DALTableAdapters.UsersTableAdapter
        Dim users As DAL.UsersDataTable = usersTA.GetData()
        Dim user As DAL.UsersRow = users.FindByUserID(userid)

       'set info state
        Me.txtUserName.Text = user.UserName
        Me.tstFirstName.Text = user.FirstName
        Me.txtLastName.Text = user.LastName
        Me.txtEmail.Text = user.Email
        Me.chkIsDisabled.Checked = user.IsDisabled

        BuildRoleTable(userid)


        Me.btnSave.Text = "Save"
    End Sub

'   #
'   #Thsi function updates a user's role
    Sub EditUserRoleChecked(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim userid = Int32.Parse(Me.ViewState("userid"))
        Dim chkRole As CheckBox = CType(sender, CheckBox)
        Dim userrolesTA As DALTableAdapters.User_RoleTableAdapter = New DALTableAdapters.User_RoleTableAdapter
        Dim userroles As DAL.User_RoleDataTable = userrolesTA.GetData()
        Dim roleid As Int32 = Int32.Parse(chkRole.Attributes("roleid"))
           If chkRole.Checked Then
               'if the role was checked as is dont find the userid roleid combination in the database then i add it
               'otherwise it's already in there so just ignore it
               If userroles.FindByUserIDRoleID(userid, roleid) Is Nothing Then
                   userrolesTA.Insert(userid, roleid)
               End If

          Else
                'if the role was not checked and i find the userid roleid combination in the database
                'then remove it
               If Not userroles.FindByUserIDRoleID(userid, roleid) Is Nothing Then
                   userrolesTA.Delete(userid, roleid)
               End If

           End If

    End Sub

    Sub NewUserRoleChecked(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim chkRole As CheckBox = CType(sender, CheckBox)
        Dim roleid As Int32 = Int32.Parse(chkRole.Attributes("roleid"))

        Dim token As Object = Session("newuserroles")
        If token Is Nothing Then
           Dim newuserroles As List(Of Int32) = New List(Of Int32)
           newuserroles.Add(roleid)
           Session("newuserroles") = newuserroles
        Else
            Dim newuserroles As List(Of Int32) = CType(Session("newuserroles"), List(Of Int32))
            newuserroles.Add(roleid)
            Session("newuserroles") = newuserroles
        End If
    End Sub
    
    Public Sub SetCreateUser()
        Me.ViewState.Remove("userid")
        Me.btnSave.Text = "Create"
        'set info state
        Me.txtPassword.Visible = True
        Me.txtPassword.Text = ""
        Me.txtUserName.Text = ""
        Me.txtUserName.ReadOnly = False
        Me.tstFirstName.Text = ""
        Me.txtLastName.Text = ""
        Me.txtEmail.Text = ""
        Me.chkIsDisabled.Checked = False
        Me.chkResetPassword.Visible = False

        'since this is a new user there are no roles to display so remove them
        tblRoles.Rows.Clear()


    End Sub



     Sub SaveEditUser()

        Dim userid = Int32.Parse(Me.ViewState("userid"))

        'load data
        Dim usersTA As DALTableAdapters.UsersTableAdapter = New DALTableAdapters.UsersTableAdapter
        Dim users As DAL.UsersDataTable = usersTA.GetData()
        Dim user As DAL.UsersRow = users.FindByUserID(userid)

        'save user info
        'user.UserName = Me.txtUserName.Text
        If Me.chkResetPassword.Checked Then
            user.IsNewUser = Me.chkResetPassword.Checked
            Dim randomNum As Random = New Random

            user.Password = "password_" & randomNum.Next(1000000)
            'notify user od the password change
            Try
                If Me.txtEmail.Text <> String.Empty Then
                    Dim strBOdy As String = "Your Charter.com Administration Tool Password hase been reset.  Please login with the temporary password below and change it. {br} Temporary Password : {password} {br} CMS Site : {server} {br} "
                    strBOdy = strBOdy.Replace("{password}", "<B>" & user.Password & "</B>")
                    strBOdy = strBOdy.Replace("{br}", "<BR/>")
                    strBOdy = strBOdy.Replace("{server}", "http://" & ConfigurationManager.AppSettings("CMSWebServer"))
                    SendEMail(ConfigurationManager.AppSettings("EMail_From"), user.Email, "Charter.com Administration Tool Password", strBOdy, True)
                End If
            Catch ex As Exception

            End Try
        End If
        user.FirstName = Me.tstFirstName.Text
        user.LastName = Me.txtLastName.Text
        user.Email = Me.txtEmail.Text
        user.IsDisabled = Me.chkIsDisabled.Checked




        'update user info database
        usersTA.Update(user)
      

     End Sub

    Sub SaveCreateUser()
        'get the current user's userid
        Dim parent As AdminPage = CType(Me.Page, AdminPage)
        Dim createdByID As Int32 = parent.CurrentUserID

        'insert the data
        Dim usersTA As DALTableAdapters.UsersTableAdapter = New DALTableAdapters.UsersTableAdapter
        Dim CMS As New CMS.CMSService()
        CMS.Credentials = Net.CredentialCache.DefaultNetworkCredentials
        Dim isDuplicateUser As Boolean = False
        Dim intId As Int32 = CMS.GetUserID(Replace(Me.txtUserName.Text, "chtr\", ""))

'       if no user was found insert the row and send an email out to the new user
        If intId = 0 Then
            usersTA.Insert(Me.txtUserName.Text, Me.txtPassword.Text, 0, Me.tstFirstName.Text, Me.txtLastName.Text, DateTime.Now, createdByID, Me.txtEmail.Text, True, False)
            Try
                If Me.txtEmail.Text <> String.Empty Then
                    Dim strBOdy As String = ConfigurationManager.AppSettings("NewAccount_Body")
                    strBOdy = strBOdy.Replace("{username}", "<B>" & txtUserName.Text & "</B>")
                    strBOdy = strBOdy.Replace("{password}", "<B>" & txtPassword.Text & "</B>")
                    strBOdy = strBOdy.Replace("{br}", "<BR>")
                    strBOdy = strBOdy.Replace("{server}", "http://" & ConfigurationManager.AppSettings("CMSWebServer"))
                    SendEMail(ConfigurationManager.AppSettings("EMail_From"), txtEmail.Text, ConfigurationManager.AppSettings("NewAccount_Subject"), strBOdy, True)
                End If
            Catch ex As Exception

            End Try

            'raise event to page to it can update the user list     
            RaiseEvent newUserCreated()
        Else
            Me.lblErrorMessage.Text = "There is already a user with that username"
            Me.lblErrorMessage.Visible = True
        End If


    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If btnSave.Text = "Create" Then
            SaveCreateUser()
        Else
            SaveEditUser()
        End If

    End Sub



    Private Sub SendEMail(ByVal FromMailID As String, ByVal ToMailID As String, ByVal Subject As String, ByVal Body As String, Optional ByVal isHTML As Boolean = False)
            Try
                Dim from_Config As String = ConfigurationManager.AppSettings("SMTPSERVER")
                Dim client As New SmtpClient(from_Config)
                Dim from As String = FromMailID
                Dim strSPlit() As String
                strSPlit = ToMailID.Split(";")
                For i As Integer = 0 To strSPlit.Length - 1
                    Dim mailMsg As New MailMessage(from, strSPlit(i))
                    With mailMsg
                        .Subject = Subject
                        .Body = Body
                    End With
                    mailMsg.IsBodyHtml = isHTML
                    client.SendAsync(mailMsg, Nothing)
                Next

                client = Nothing
            Catch ex As Exception

            End Try
    End Sub

End Class
