Imports CAMS_ADMIN
Imports CAMS_BL
Imports System.Data
Imports System.Text

Public Class frmUsers
    Inherits CAMSBasePage

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object
    Protected WithEvents txtSurname As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtAbbr As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtName As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtEmail As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtLogin As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlAccessGroup As System.Web.UI.WebControls.DropDownList
    Protected WithEvents chkActNotification As System.Web.UI.WebControls.CheckBox
    Protected WithEvents chkAllowInternetCnn As System.Web.UI.WebControls.CheckBox
    Protected WithEvents dgResults As System.Web.UI.WebControls.DataGrid
    Protected WithEvents lblTotalRecords As System.Web.UI.WebControls.Label
    Protected WithEvents lblTotalPages As System.Web.UI.WebControls.Label
    Protected WithEvents txtRecordsPerPage As System.Web.UI.WebControls.TextBox
    Protected WithEvents imgBtnRefresh As System.Web.UI.WebControls.ImageButton
    Protected WithEvents PagingBar1 As PACNET.WebControls.PagingBar
    Protected WithEvents pnlResults As System.Web.UI.WebControls.Panel
    Protected WithEvents lblMsgNoResults As System.Web.UI.WebControls.Label
    Protected WithEvents pnlNoResults As System.Web.UI.WebControls.Panel
    Protected WithEvents hdEvent As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hdAction As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hdRowId As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hdItemID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hdPassword As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents lblValLogin As System.Web.UI.WebControls.Label
    Protected WithEvents lblValAbbrev As System.Web.UI.WebControls.Label
    Protected WithEvents btnDelete As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents btnSave As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents btnCancel As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents Button1 As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents btnAdd As System.Web.UI.HtmlControls.HtmlInputButton
    Protected WithEvents mnuCams As Menu

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Const FIRST_PAGE As Integer = 1

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Access Validation to page
        If Not Me.IsPostBack Then
            Dim oEC_User As EC_User = Me.GetUserFromSession

            If Not oEC_User Is Nothing Then
                If Me.HasAccessTo(Me.GetControlID("frmUsers.aspx"), oEC_User.AccessGroup) = False Then
                    Me.RedirectToMsgPage(Constants.CONST_ERROR_ACCESSDENIED_TOPAGE)
                End If
            End If

            ValidateUser(oEC_User)

        End If
        'End Access Validation

        'Menu
        mnuCams.CurrentGroup = Constants.MENU_SETTINGS_ID
        mnuCams.CurrentItem = Constants.MENU_SETTINGS_USERS_ID
        'End Menu

        'Attributes for some controls
        txtRecordsPerPage.Attributes.Add("onKeyPress", "fnOnlyDigits(event,'decNo')")
        chkActNotification.Attributes.Add("onclick", "chkActNotification_onCheckedChanged()")
        lblValAbbrev.Visible = False
        lblValLogin.Visible = False

        If txtRecordsPerPage.Text.Trim.Equals(String.Empty) OrElse Convert.ToInt32(txtRecordsPerPage.Text) < 1 Then
            txtRecordsPerPage.Text = "100"
        End If
        'End attributes

        'Initial values
        If Not Me.IsPostBack Then
            LoadDropDownLists()
            hdAction.Value = "I" 'setting as default action, I = Insert
            RefreshResults(FIRST_PAGE, txtRecordsPerPage.Text)
        End If
        'End Initial values

        'Postback
        If IsPostBack Then
            If hdEvent.Value = "save" Then
                Save()
            ElseIf hdEvent.Value = "selrow" Then
                SelectRow(Convert.ToInt32(hdRowId.Value))
                ShowItem(Convert.ToInt32(hdRowId.Value))
            ElseIf hdEvent.Value = "cancel" Then
                SetCancel()
            ElseIf hdEvent.Value = "add" Then
                btnAdd_Click()
            End If

        End If
        'End postback

        'Added by Raul Callupe
        If Me.IsPostBack = False Then
            Dim stbOutput As New StringBuilder
            stbOutput.Append("<script language='Javascript'>")
            stbOutput.Append("var pag = window.parent.frames(0);")
            stbOutput.Append("pag.document.all.lblPath.innerHTML='Settings/Users'")
            stbOutput.Append("</script>")
            Response.Write(stbOutput.ToString)
        End If
        'End Added

    End Sub

    Private Sub ValidateUser(ByVal oUser As EC_User)
        If Not oUser Is Nothing Then

            If oUser.AccessGroup = Constants.CONST_ACCESSGROUP_MA Then
                btnSave.Visible = True
                btnDelete.Visible = True
                btnAdd.Visible = True

                txtSurname.ReadOnly = False
                txtAbbr.ReadOnly = False
                txtEmail.ReadOnly = False
                txtLogin.ReadOnly = False
                txtName.ReadOnly = False
                txtPassword.ReadOnly = False
                ddlAccessGroup.Enabled = True
                chkActNotification.Enabled = True
                chkAllowInternetCnn.Enabled = True
            Else
                btnSave.Visible = False
                btnDelete.Visible = False
                btnAdd.Visible = False
                txtSurname.ReadOnly = True
                txtAbbr.ReadOnly = True
                txtEmail.ReadOnly = True
                txtLogin.ReadOnly = True
                txtName.ReadOnly = True
                txtPassword.ReadOnly = True
                ddlAccessGroup.Enabled = False
                chkActNotification.Enabled = False
                chkAllowInternetCnn.Enabled = False
            End If
        End If

    End Sub

#Region "Loading Dropdownlists"

    Private Sub LoadDropDownLists()
        Dim oCC_User As New CC_User
        Dim dsData As DataSet

        Try
            dsData = oCC_User.GetDataForControls

            If Not dsData Is Nothing Then
                Util.FillDropDownList(dsData.Tables("ACCESSGROUPS").DefaultView, ddlAccessGroup, "IDSEQUENCE", "DESCRIPTION", True, New ListItem("", ""))
            Else
                Throw New Exception("No data")
            End If

        Catch ex As Exception
            ddlAccessGroup.Items.Clear()
            ddlAccessGroup.Items.Add(New ListItem("Empty", ""))
        End Try

    End Sub

#End Region

#Region "Refresh datagrid"

    Private Sub setNoRecordsFounds(ByVal bValue As Boolean)
        pnlNoResults.Visible = bValue
        pnlResults.Visible = Not bValue
    End Sub

    Private Sub RefreshResults(ByVal nPage As Integer, ByVal nRecordsPerPage As Integer)
        Dim oCC_User As New CC_User
        Dim dsResults As DataSet

        Try
            dsResults = oCC_User.GetUsers(nPage, txtRecordsPerPage.Text)

            If Not dsResults Is Nothing Then
                If dsResults.Tables(0).Rows.Count = 0 Then
                    setNoRecordsFounds(True)
                ElseIf dsResults.Tables(0).Rows(0)("record_count") < Convert.ToInt32(txtRecordsPerPage.Text) Then
                    PagingBar1.TotalNPages = FIRST_PAGE
                Else
                    Dim dDec = dsResults.Tables(0).Rows(0)("record_count") / Convert.ToInt32(txtRecordsPerPage.Text)
                    Dim nEnt = Decimal.Round(dDec, 0)
                    Dim nPages As Integer

                    If dDec > nEnt Then
                        nPages = nEnt + 1
                    Else
                        nPages = nEnt
                    End If
                    PagingBar1.TotalNPages = nPages
                End If

                If dsResults.Tables(0).Rows.Count > 0 Then
                    dgResults.CurrentPageIndex = 0
                    dgResults.DataSource = dsResults
                    dgResults.DataBind()

                    PagingBar1.PagesDisplayed = Convert.ToInt32(txtRecordsPerPage.Text)
                    PagingBar1.CurrentPage = nPage
                    lblTotalRecords.Text = dsResults.Tables(0).Rows(0)("record_count").ToString()
                    lblTotalPages.Text = PagingBar1.TotalNPages

                    setNoRecordsFounds(False)
                Else
                    setNoRecordsFounds(True)
                End If
            Else
                setNoRecordsFounds(True)
            End If

        Catch ex As Exception
            dsResults = Nothing
            setNoRecordsFounds(True)
        End Try

    End Sub

#End Region

#Region "Controls' events"

    Private Sub btnAdd_Click()
        hdItemID.Value = String.Empty
        txtSurname.Text = String.Empty
        txtName.Text = String.Empty
        txtAbbr.Text = String.Empty
        txtEmail.Text = String.Empty
        txtLogin.Text = String.Empty
        txtPassword.Text = String.Empty
        hdPassword.Value = String.Empty

        chkActNotification.Checked = False
        chkAllowInternetCnn.Checked = False

        Try
            Util.SelectValueFromDropDown(ddlAccessGroup, String.Empty)
        Catch

        End Try

        'setting actions
        hdEvent.Value = ""
        hdAction.Value = "I"
        hdRowId.Value = ""
    End Sub

    Private Sub SetCancel()
        Me.RedirectToHome()
    End Sub

#End Region

#Region "Save"

    Private Sub Save()
        If hdAction.Value.Equals("I") Then
            Insert()
        ElseIf hdAction.Value.Equals("U") Then
            Update()
        ElseIf hdAction.Value.Equals("D") Then
            Delete()
        End If

    End Sub

    Private Sub Insert()
        Dim oEC_User As EC_User = SetProperties()
        Dim oCC_User As New CC_User
        Dim strMsg As String

        If Not oEC_User Is Nothing Then
            If oCC_User.SaveUser(oEC_User, strMsg) Then
                Me.btnAdd_Click()
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))
            Else
                If strMsg = "USEREXISTS" Then
                    lblValAbbrev.Text = "Abbrev. exists for <br>the access group selected"
                    lblValAbbrev.Visible = True
                ElseIf strMsg = "LOGINEXISTS" Then
                    lblValLogin.Text = "Login exists in database"
                    lblValLogin.Visible = True
                End If
            End If

        End If

    End Sub

    Private Sub Update()
        Dim oEC_User As EC_User = SetProperties()
        Dim oCC_User As New CC_User
        Dim strMsg As String

        If Not oEC_User Is Nothing Then
            If oCC_User.UpdateUser(oEC_User, strMsg) = False Then
                If strMsg = "ERROR_LOGIN" Then
                    lblValLogin.Text = "Login cannot be modified"
                    lblValLogin.Visible = True
                ElseIf strMsg = "ERROR_TA" Then
                    Me.RedirectToMsgPage(Constants.CONST_ERROR_USER_IN_CASE_TA)
                ElseIf strMsg = "ERROR_HA" Then
                    Me.RedirectToMsgPage(Constants.CONST_ERROR_USER_IN_CASE_HA)
                ElseIf strMsg = "ERROR_GO" Then
                    Me.RedirectToMsgPage(Constants.CONST_ERROR_USER_IN_GRANTOFFICE)
                End If
            Else
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))

                If hdRowId.Value.Trim.Equals(String.Empty) = False Then
                    SelectRow(Convert.ToInt32(hdRowId.Value))
                    ShowItem(Convert.ToInt32(hdRowId.Value))
                End If
            End If

        End If
    End Sub

    Private Sub Delete()
        Dim oEC_User As EC_User = SetProperties()
        Dim oCC_User As New CC_User
        Dim strMsg As String

        If Not oEC_User Is Nothing Then
            If oCC_User.DeleteUser(oEC_User, strMsg) = False Then
                Me.RedirectToMsgPage(Constants.CONST_ERROR_USER_NOTDELETED)
            Else
                btnAdd_Click()
                RefreshResults(FIRST_PAGE, Convert.ToInt32(txtRecordsPerPage.Text))
            End If

        End If
    End Sub

    Private Function SetProperties() As EC_User
        Dim oEC_User As New EC_User
        Dim oEC_ActiveUser As EC_User = Me.GetUserFromSession

        With oEC_User
            If hdItemID.Value.Equals(String.Empty) = False Then
                .UserID = hdItemID.Value
            End If
            .Surname = txtSurname.Text.Trim.ToUpper
            .Name = txtName.Text.Trim.ToUpper
            .Abbreviation = txtAbbr.Text.Trim.ToUpper
            .Email = txtEmail.Text.Trim
            .Login = txtLogin.Text.Trim
            .Password = Util.Encrypt(txtPassword.Text.Trim)
            .AccessGroup = ddlAccessGroup.SelectedValue

            If chkActNotification.Checked Then
                .EmailNotif = "Y"
            Else
                .EmailNotif = "N"
            End If

            If chkAllowInternetCnn.Checked Then
                .ConnectOutside = "Y"
            Else
                .ConnectOutside = "N"
            End If

            If Not oEC_ActiveUser Is Nothing Then
                .AddedBy = oEC_ActiveUser.Login
                .ChangedBy = oEC_ActiveUser.Login
            End If

        End With

        Return oEC_User

    End Function

#End Region

#Region "Common methods"

    Private Sub dgResults_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgResults.ItemDataBound
        If e.Item.ItemType <> ListItemType.Header Then
            e.Item.Cells(0).Text = "<a href=""#"" onclick=""fnSelRow(" & e.Item.ItemIndex.ToString & ")""><img src=""../images/view.gif"" border=0></a>"
        End If

    End Sub

    Private Sub SelectRow(ByVal rowID As Integer)

        Try
            If dgResults.Items.Count > 0 Then
                'Setting the action as an updating
                hdAction.Value = "U"
                hdItemID.Value = dgResults.Items(rowID).Cells(1).Text

                For i As Integer = 0 To dgResults.Items.Count - 1
                    If i Mod 2 = 0 Then
                        dgResults.Items(i).CssClass = "PAGE_GRID_ITEM"
                    Else
                        dgResults.Items(i).CssClass = "PAGE_GRID_ALTERNATING"
                    End If
                Next

                dgResults.Items(rowID).CssClass = "PAGE_GRID_ITEM_SELECTED"
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ShowItem(ByVal rowID As Integer)
        Dim strItemID As String

        Try
            If dgResults.Items.Count > 0 Then

                strItemID = dgResults.Items(rowID).Cells(1).Text.Trim

                If strItemID.Equals(String.Empty) = False Then
                    LoadItem(strItemID)
                End If
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub LoadItem(ByVal prmItemID As Integer)
        Dim oCC_User As New CC_User
        Dim oEC_User As EC_User = oCC_User.GetUserByID(prmItemID)

        If Not oEC_User Is Nothing Then
            With oEC_User
                hdItemID.Value = .UserID.ToString
                txtSurname.Text = .Surname
                txtName.Text = .Name
                txtAbbr.Text = .Abbreviation
                txtLogin.Text = .Login
                'txtPassword.Text = .Password
                hdPassword.Value = Util.Encrypt(.Password)
                txtEmail.Text = .Email

                Try
                    Util.SelectValueFromDropDown(ddlAccessGroup, .AccessGroup)
                Catch

                End Try

                If .EmailNotif = "Y" Then
                    chkActNotification.Checked = True
                Else
                    chkActNotification.Checked = False
                End If

                If .ConnectOutside = "Y" Then
                    chkAllowInternetCnn.Checked = True
                Else
                    chkAllowInternetCnn.Checked = False
                End If

            End With
        End If
    End Sub

#End Region

#Region "Pagination"

    Private Sub txtRecordsPerPage_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtRecordsPerPage.TextChanged
        PagingBar1.CurrentPage = FIRST_PAGE
        PagingBar1.TotalNPages = FIRST_PAGE
        PagingBar1.PagesDisplayed = txtRecordsPerPage.Text
        RefreshResults(FIRST_PAGE, txtRecordsPerPage.Text)
    End Sub

    Private Sub PagingBar1_ChangePage(ByVal sender As Object, ByVal e As PACNET.WebControls.ChangePageEventArgs) Handles PagingBar1.ChangePage
        RefreshResults(e.SelectedPage, txtRecordsPerPage.Text)
    End Sub

#End Region

End Class
