Public Class FrmIngresoContrato
    Public Sub New(ByRef owner As Form)
        idContrato = 0
        InitializeComponent()
        Me.Owner = owner

        If TypeOf owner Is FrmParametros Then
            LblIndicacion.Text = "Ingrese el Contrato para importar Empresas"
            BtnImportar.Text = "Importar"
        Else
            LblIndicacion.Text = "Ingrese el Contrato para cargar Empresas"
            BtnImportar.Text = "Ingresar"
        End If
    End Sub

    Private Sub BtnImportar_Click(sender As Object, e As EventArgs) Handles BtnImportar.Click
        ProcesarContrato()
    End Sub

    Private Sub ProcesarContrato()
        If Not TxtContrato.Text.Equals("") And Not IsNothing(TxtContrato.Text) Then

            If TypeOf Owner Is FrmParametros Then
                If ValidarContrato() Then
                    ImportarEmpresas()
                    Me.Close()
                Else
                    MessageBox.Show("El contrato ingresado no exite", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    TxtContrato.Select()
                    TxtContrato.SelectAll()
                End If
            Else
                If ValidarContrato() Then
                    idContrato = CInt(TxtContrato.Text)
                    Me.Close()
                Else
                    MessageBox.Show("El contrato ingresado no exite", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    TxtContrato.Select()
                    TxtContrato.SelectAll()
                End If
            End If

        Else
            MessageBox.Show("Debe ingresar un contrato", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
            TxtContrato.Select()
            TxtContrato.SelectAll()
        End If
    End Sub

    Private Function ValidarContrato() As Boolean
        Dim result As Boolean = False
        Dim bbdd As String
        Dim sql As String
        If TypeOf Owner Is FrmParametros Then
            bbdd = conexionMaestra
            sql = $"SELECT DISTINCT id_contrato FROM Empresas WHERE id_contrato = {TxtContrato.Text}"
        Else
            bbdd = conexionLocal
            sql = $"SELECT DISTINCT idContrato FROM Empresas WHERE idContrato = {TxtContrato.Text}"
        End If
        Dim conn As New Conexion(bbdd)
        Dim validaContrato As String = conn.ObtenerValor(sql)

        If validaContrato <> "" Then
            result = True
        End If

        conn.CerrarBD()
        Return result
    End Function

    Private Function ImportarEmpresas() As Boolean
        Try
            Dim result As Boolean = False

            Dim conn As New Conexion(conexionMaestra)
            Dim sql As String = $"SELECT id_empresa, num_legal, empresa, P.Pais, '1' AS activo, id_contrato FROM Empresas E JOIN Paises P ON E.pais = P.id WHERE id_contrato = {TxtContrato.Text}"

            Dim dtEmp = conn.ObtenerDataTable(sql, New List(Of SqlClient.SqlParameter))

            If dtEmp.Rows.Count > 0 Then
                Dim connLocal As New Conexion(conexionLocal)
                Dim mensajeError As String = ""

                For Each emp As DataRow In dtEmp.Rows
                    Dim empresaCrear As New ClsEmpresasCrear(connLocal)

                    Dim ok As Boolean = False

                    Try
                        Dim argumentosEmpresa As New EmpresasCrearArgumentos() With {
                            .Id = emp.Item("id_empresa"),
                            .NumeroLegal = emp.Item("num_legal"),
                            .NombreLegal = emp.Item("empresa"),
                            .Pais = emp.Item("pais"),
                            .Activo = emp.Item("activo"),
                            .IdContrato = emp.Item("id_contrato")}
                        If empresaCrear.Crear(argumentosEmpresa, mensajeError) Then
                            result = True
                        Else
                            result = False
                            Exit For
                        End If
                    Catch ex As Exception
                        mensajeError += vbNewLine + ex.Message
                    End Try
                Next

                If result Then
                    MessageBox.Show("Empresas importadas correctamente.")
                    conn.Dispose()
                    Me.Close()
                Else
                    MsgBox(mensajeError)
                    conn.Dispose()
                    TxtContrato.Focus()
                    TxtContrato.SelectAll()
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Function

    Private Sub Keypress_Enter(sender As Object, e As KeyPressEventArgs) Handles TxtContrato.KeyPress, Me.KeyPress
        If Not Char.IsDigit(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
            ' Cancela la pulsación de tecla
            e.Handled = True
        Else
            If e.KeyChar = Chr(13) Then
                ProcesarContrato()
                e.Handled = True
            ElseIf e.KeyChar = Chr(27) Then
                e.Handled = True
                Me.Close()
            End If
        End If
    End Sub

    Private Sub LinkSalir_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs)
        Me.Close()
    End Sub
End Class