Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Friend Class frmCadastroClasses
    Inherits System.Windows.Forms.Form

    Private mItem As System.Windows.Forms.ListViewItem ' Objeto que controla a linha do listview
    Dim vCodigo As String
    Dim vResp As Short
    Dim vNew As Boolean
    Dim vCodOld As String
    Dim vMascara As String

#Region "Propriedades"

    Private Sub FrmCadastroClasse_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load

        Try

            SetaFrameDados(False)
            cmdEditar.Enabled = False
            cmdSalvar.Enabled = False
            cmdExcluir.Enabled = False
            vMascara = GetConfig("conta.Mascara")
            mskConta_Faturamento.Mask = vMascara
            mskConta_Faturamento_parc.Mask = vMascara
            desativaCampos(2)
            lClear()
            lAtualizaList()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: FrmCadastroClasse_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lvwClasses_ColumnClick(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ColumnClickEventArgs) Handles lvwClasses.ColumnClick

        Dim ColumnHeader As System.Windows.Forms.ColumnHeader = lvwClasses.Columns(eventArgs.Column)

        Try
            lvwClasses.ListViewItemSorter = New ListViewItemComparer(eventArgs.Column)
            lvwClasses.Sort()
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lvwClasses_ColumnClick" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lvwClasses_DoubleClick(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles lvwClasses.DoubleClick

        Try
            If lvwClasses.Items.Count > 0 Then

                cmdEditar.Enabled = True
                cmdSalvar.Enabled = False
                cmdExcluir.Enabled = True

                lEdit(lvwClasses.FocusedItem.Name.Trim())
            End If
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lvwClasses_DoubleClick" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdNovo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNovo.Click

        Try

            lNew()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdNovo_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try


    End Sub

    Private Sub cmdEditar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdEditar.Click

        Try

            lEdit()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdEditar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdSalvar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvar.Click

        Try


            If vNew = True Then

                If lInsert() Then
                    MessageBox.Show("Classe criado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    SetaFrameDados(False)
                    cmdEditar.Enabled = False
                    cmdSalvar.Enabled = False
                    cmdExcluir.Enabled = False
                    desativaCampos(2)
                    lClear()
                    lAtualizaList()
                Else
                    MessageBox.Show("Classe não pode ser criado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

            Else

                If lUpdate() Then
                    MessageBox.Show("Classe atualizado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    SetaFrameDados(False)
                    cmdEditar.Enabled = False
                    cmdSalvar.Enabled = False
                    cmdExcluir.Enabled = False
                    desativaCampos(2)
                    lClear()
                    lAtualizaList()
                Else
                    MessageBox.Show("Classe não pode ser atualizado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If

            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdSalvar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdCancelar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancelar.Click

        Try

            lCancel()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdCancelar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdExcluir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExcluir.Click

        Dim objClasse As New entidadeClasse


        Try

            vResp = MessageBox.Show("Deseja Realmente Excluir a Classe de Código: " & vCodOld & " ?", "Confirmação de Exclusão", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

            If vResp = DialogResult.Yes Then

                objClasse.CODIGO = vCodOld

                If Not lDelete(objClasse) Then
                    MessageBox.Show("Classe não pode ser excluído!", "Confirmação de Exclusão", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                Else
                    MessageBox.Show("Classe excluída com sucesso!", "Confirmação de Exclusão", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    SetaFrameDados(False)
                    cmdEditar.Enabled = False
                    cmdSalvar.Enabled = False
                    cmdExcluir.Enabled = False
                    desativaCampos(2)
                    lClear()
                    lAtualizaList()
                End If


            ElseIf vResp = DialogResult.Cancel Then
                Exit Sub
            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdExcluir_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try


    End Sub

    Private Sub cmdSair_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSair.Click
        Try

            lClose()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdSair_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub txtCodigo_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtCodigo.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii = 27 Then
                txtCodigo.Text = ""
                txtDescricao.Text = ""
                txtCodigo.Focus()
            ElseIf KeyAscii = 13 Then
                cmdSalvar_Click(cmdSalvar, New System.EventArgs())
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtCodigo_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub txtDescricao_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtDescricao.KeyPress
        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try
            If KeyAscii = 27 Then
                txtCodigo.Text = ""
                txtDescricao.Text = ""
                txtCodigo.Focus()
            ElseIf KeyAscii = 13 Then
                cmdSalvar_Click(cmdSalvar, New System.EventArgs())
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtDescricao_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub FrmCadastroClasse_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii = System.Windows.Forms.Keys.Escape Then
                Call Me.Close()
            ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: FrmCadastroClasse_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

#End Region

#Region "Métodos"

    Private Sub lAtualizaList()

        Dim objClasse As entidadeClasse

        Try
            CarregarGrid(objClasse)

            If lvwClasses.Items.Count <> 0 Then

                lvwClasses.Focus()
                lvwClasses.Items.Item(0).Selected = True
                lvwClasses.FocusedItem = lvwClasses.Items.Item(0)
                lvwClasses.Items.Item(0).EnsureVisible()

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lAtualizaList" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub PrepararListView()

        Try

            lvwClasses.Items.Clear()
            lvwClasses.Columns.Clear()
            lvwClasses.Columns.Add(String.Empty, "Código", 50)
            lvwClasses.Columns.Add(String.Empty, "Descrição", 400)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PrepararListView" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub CarregarGrid(ByRef objClasse As entidadeClasse)

        Try
            PrepararListView()
            For Each objClasseFor As entidadeClasse In New repositorioClasse().Select(objClasse)
                AddListItem(mItem, objClasseFor)
            Next
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregarGrid" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub AddListItem(ByRef xItem As System.Windows.Forms.ListViewItem, ByRef objClasse As entidadeClasse)

        Try

            xItem = lvwClasses.Items.Add(objClasse.CODIGO.ToString(), objClasse.CODIGO, String.Empty)

            If (String.IsNullOrEmpty(objClasse.DESCRICAO)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objClasse.DESCRICAO)
            End If

            If (String.IsNullOrEmpty(objClasse.CONTA_FATURAMENTO)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objClasse.CONTA_FATURAMENTO)
            End If

            If (String.IsNullOrEmpty(objClasse.CONTA_FATURAMENTO_PARC)) Then
                xItem.SubItems.Add(Space(1))
            Else
                xItem.SubItems.Add(objClasse.CONTA_FATURAMENTO_PARC)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: AddListItem" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherValoresList(ByRef Items As String)

        vCodigo = Items

        Dim Item As ListViewItem



        Try

            For Each Item In lvwClasses.Items

                If Item.Name = vCodigo Then

                    'Pega a Coluna 0
                    txtCodigo.Text = IIf(String.IsNullOrEmpty((Item.Text)), " ", (Item.Text))
                    vCodOld = IIf(String.IsNullOrEmpty((Item.Text)), " ", (Item.Text))

                    'Para pegar os SubItems e so fazer o seguinte
                    txtDescricao.Text = IIf(String.IsNullOrEmpty((Item.SubItems(1).Text)), " ", (Item.SubItems(1).Text))
                    mskConta_Faturamento.Text = IIf(String.IsNullOrEmpty((Item.SubItems(2).Text)), " ", (Item.SubItems(2).Text))
                    mskConta_Faturamento_parc.Text = IIf(String.IsNullOrEmpty((Item.SubItems(3).Text)), " ", (Item.SubItems(3).Text))
                    ativaCampos(2)
                    desativaCampos(1)

                End If


            Next

            Item = Nothing


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherValoresList" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub SetaFrameDados(ByVal modo As Boolean)

        Try

            frameDados1.Enabled = modo
            frameDados1.Visible = modo

            If modo = True Then
                lvwClasses.Enabled = False
                cmdNovo.Enabled = False
                cmdEditar.Enabled = False
                cmdExcluir.Enabled = False
                cmdSair.Enabled = False
            ElseIf modo = False Then
                lvwClasses.Enabled = True
                cmdNovo.Enabled = True
                cmdEditar.Enabled = True
                cmdExcluir.Enabled = True
                cmdSair.Enabled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: SetaFrameDados" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    'Ativa os campos para edição. (1 - destrava / 2 - destrava e muda a cor)
    Private Sub ativaCampos(ByRef modo As Short)

        Try

            If modo = 1 Then
                txtCodigo.ReadOnly = False
                txtDescricao.ReadOnly = False
            ElseIf modo = 2 Then
                txtCodigo.ReadOnly = False
                txtDescricao.ReadOnly = False
                txtCodigo.BackColor = System.Drawing.ColorTranslator.FromOle(&H80000005)
                txtDescricao.BackColor = System.Drawing.ColorTranslator.FromOle(&H80000005)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: ativaCampos" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    'Desativa os campos para edição. (1 - trava / 2 - trava e muda a cor)
    Private Sub desativaCampos(ByRef modo As Short)

        Try

            If modo = 1 Then
                txtCodigo.ReadOnly = True
                txtDescricao.ReadOnly = True
            ElseIf modo = 2 Then
                txtCodigo.ReadOnly = True
                txtDescricao.ReadOnly = True
                txtCodigo.BackColor = System.Drawing.ColorTranslator.FromOle(&H80000004)
                txtDescricao.BackColor = System.Drawing.ColorTranslator.FromOle(&H80000004)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: desativaCampos" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lEdit(ByRef Item As String)

        vCodigo = Item

        Try

            PreencherValoresList(vCodigo)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lEdit" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lNew()

        Try

            vNew = True

            ativaCampos(2)
            SetaFrameDados(True)
            cmdEditar.Enabled = False
            cmdSalvar.Enabled = True
            cmdExcluir.Enabled = False

            lClear()


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lNew" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lClear()

        Try

            txtCodigo.Text = String.Empty
            txtDescricao.Text = String.Empty
            txtCodigo.Focus()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lClear" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lCancel()

        Try

            SetaFrameDados(False)
            cmdEditar.Enabled = False
            cmdSalvar.Enabled = False
            cmdExcluir.Enabled = False
            desativaCampos(2)
            lClear()
            lAtualizaList()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lCancel" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lEdit()

        Try

            vNew = False
            SetaFrameDados(True)
            ativaCampos(1)
            cmdSalvar.Enabled = True
            txtDescricao.Focus()
            txtDescricao.SelectionStart = 0
            txtDescricao.SelectionLength = Len(txtDescricao.Text)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lEdit" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lClose()

        Try

            Close()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lClose" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Function lInsert() As Boolean

        Dim objClasse As New entidadeClasse
        Dim repositorioClasse As New repositorioClasse

        Try

            objClasse.CODIGO = Trim(IIf(String.IsNullOrEmpty((txtCodigo.Text)), " ", txtCodigo.Text))
            objClasse.DESCRICAO = Trim(IIf(String.IsNullOrEmpty((txtDescricao.Text)), " ", txtDescricao.Text))
            objClasse.CONTA_FATURAMENTO = Trim(IIf(String.IsNullOrEmpty((mskConta_Faturamento.Text)), " ", Replace(mskConta_Faturamento.Text, ",", ".")))
            objClasse.CONTA_FATURAMENTO_PARC = Trim(IIf(String.IsNullOrEmpty((mskConta_Faturamento.Text)), " ", Replace(mskConta_Faturamento.Text, ",", ".")))


            repositorioClasse.Insert(objClasse)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lInsert" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End Try

    End Function

    Private Function lUpdate() As Boolean

        Dim objClasse As New entidadeClasse
        Dim repositorioClasse As New repositorioClasse


        Try

            objClasse.CODIGO = Trim(IIf(String.IsNullOrEmpty((txtCodigo.Text)), " ", txtCodigo.Text))
            objClasse.DESCRICAO = Trim(IIf(String.IsNullOrEmpty((txtDescricao.Text)), " ", txtDescricao.Text))
            objClasse.GRUPOTAR = Trim(IIf(String.IsNullOrEmpty((vCodOld)), " ", vCodOld))
            objClasse.CONTA_FATURAMENTO = Trim(IIf(String.IsNullOrEmpty((mskConta_Faturamento.Text)), " ", Replace(mskConta_Faturamento.Text, ",", ".")))
            objClasse.CONTA_FATURAMENTO_PARC = Trim(IIf(String.IsNullOrEmpty((mskConta_Faturamento_parc.Text)), " ", Replace(mskConta_Faturamento_parc.Text, ",", ".")))


            repositorioClasse.Update(objClasse)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lUpdate" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End Try

    End Function

    Private Function lDelete(ByRef objClasse As entidadeClasse) As Boolean
        Dim repositorioClasse As New repositorioClasse
        Try

            repositorioClasse.Delete(objClasse)

            Return True
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lDelete" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End Try
    End Function







#End Region


End Class