Imports System.Net
Imports VERAG_PROG_ALLGEMEIN

Public Class frmAPIEinstellungen

    Dim APIBind As cEasyBinding
    Public table
    Public BIND_DB
    Private EditRow As Integer = -1
    Sub New(table, BIND_DB)
        Me.table = table
        Me.BIND_DB = BIND_DB
        InitializeComponent()
    End Sub

    Private Sub frmAPIEinstellungen_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        loadDGV()
        btnOK.Visible = True


    End Sub

    Private Sub loadDGV(Optional sqlwhere As String = "")

        Try
            APIBind = New cEasyBinding(BIND_DB)


            If sqlwhere = "" Then

                APIBind.initBinding("SELECT [api_active],[api_productive], [api_program],[api_id],[api_url] ,[api_user],[api_password] ,[api_UseToken],[api_token] ,[api_description], [api_debugpath] FROM " & table & " WHERE api_productive = " & IIf(cbxProduktivsystem.Checked, "1", "0"), table)
            Else

                APIBind.initBinding("Select [api_active], [api_productive], [api_program], [api_id], [api_url], [api_user], [api_password], [api_useToken], [api_token], [api_description], [api_debugpath]  FROM " & table & " WHERE api_productive = " & IIf(cbxProduktivsystem.Checked, "1", "0") & sqlwhere, table)

            End If

            DataGridView.DataSource = APIBind.bindingdataTable

            With DataGridView

                If .Columns.Count > 0 Then

                    .Columns("api_id").Visible = False
                    .Columns("api_active").HeaderText = "Aktiv"
                    .Columns("api_active").Width = 50
                    .Columns("api_productive").HeaderText = "Produktiv"
                    .Columns("api_productive").Width = 70
                    .Columns("api_program").HeaderText = "Programm"
                    .Columns("api_program").Width = 80
                    .Columns("api_url").HeaderText = "URL"
                    .Columns("api_url").Width = 150
                    .Columns("api_user").HeaderText = "User"
                    .Columns("api_user").Width = 100
                    .Columns("api_password").HeaderText = "PW"
                    .Columns("api_password").Width = 100
                    .Columns("api_useToken").HeaderText = "Token"
                    .Columns("api_useToken").Width = 40
                    .Columns("api_Token").HeaderText = "Token-Key"
                    .Columns("api_Token").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                    .Columns("api_description").HeaderText = "Beschreibung"
                    .Columns("api_description").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                    .Columns("api_debugpath").HeaderText = "Debug-File"
                    .Columns("api_debugpath").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill


                    If .Columns("isRunning") Is Nothing Then

                        Dim c As New DataGridViewImageColumn
                        c.Name = "isRunning" : c.HeaderText = "Online"
                        c.Image = New Bitmap(1, 1)
                        c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                        c.DefaultCellStyle.Tag = "Online"
                        .Columns.Add(c)

                    End If

                    If .Columns("pathToFile") Is Nothing Then

                        Dim c As New DataGridViewImageColumn
                        c.Name = "pathToFile" : c.HeaderText = "Debug-Pfad"
                        c.Image = New Bitmap(1, 1)
                        c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                        c.DefaultCellStyle.Tag = "pathToFile"
                        .Columns.Add(c)

                    End If

                    For Each r As DataGridViewRow In .Rows

                        If r.Cells("api_url").Value Is DBNull.Value Then
                            r.DefaultCellStyle.ForeColor = Color.Gray
                        ElseIf CBool(r.Cells("api_active").Value) = False Then
                            r.DefaultCellStyle.ForeColor = Color.Gray
                        End If

                        If r.Cells("api_url").Value IsNot DBNull.Value AndAlso CheckAddress(r.Cells("api_url").Value, r.Cells("api_user").Value, r.Cells("api_password").Value) Then
                            DirectCast(r.Cells("isRunning"), DataGridViewImageCell).Value = My.Resources.ok
                        Else
                            DirectCast(r.Cells("isRunning"), DataGridViewImageCell).Value = My.Resources.del
                        End If


                        If r.Cells("api_debugpath").Value IsNot DBNull.Value AndAlso r.Cells("api_debugpath").Value IsNot Nothing AndAlso (r.Cells("api_debugpath").Value.ToString.StartsWith("\\") Or r.Cells("api_debugpath").Value.ToString.StartsWith("C:\")) Then
                            DirectCast(r.Cells("pathToFile"), DataGridViewImageCell).Value = My.Resources.search

                        End If

                    Next
                End If


            End With



        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Sub DataGridView_DefaultValuesNeeded(sender As Object, e As DataGridViewRowEventArgs) Handles DataGridView.DefaultValuesNeeded
        Try

            e.Row.Cells("api_active").Value = True
            e.Row.Cells("api_productive").Value = False
            e.Row.Cells("api_token").Value = False

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub


    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click

        If DataGridView.Columns.Count = 0 Or DataGridView.SelectedRows.Count = 0 Then 'alles gelöscht oder markierte Zeile gelöscht
            APIBind.updateBinding()
            Exit Sub
        End If

        If DataGridView.CurrentRow.Cells("api_url").ToString <> "" AndAlso DataGridView.CurrentRow.Cells("api_user").ToString <> "" AndAlso DataGridView.CurrentRow.Cells("api_password").ToString <> "" AndAlso EditRow >= 0 Then
            APIBind.updateBinding()
        End If

    End Sub


    Private Sub DataGridView_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView.EditingControlShowing
        EditRow = DataGridView.CurrentRow.Index
    End Sub

    Private Sub DataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView.SelectionChanged
        If EditRow >= 0 Then
            Dim new_row As Integer = EditRow
            EditRow = -1
            DataGridView.CurrentCell = DataGridView.Rows(new_row).Cells(
                DataGridView.CurrentCell.ColumnIndex)
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        If DataGridView.SelectedRows.Count = 0 Then Exit Sub
    End Sub

    Private Function CheckAddress(url As String, user As String, pw As String) As Boolean

        If url = "" Then Return False

        If Not url.Contains("ftp") Then

            Try
                Dim request As WebRequest
                request = WebRequest.Create(url)
                Dim response As WebResponse = request.GetResponse()
            Catch ex As Exception
                Return False
            End Try
            Return True
        Else

            If url.StartsWith("ftp") Then
                Dim request As FtpWebRequest
                request = WebRequest.Create(url)
                request.Credentials = New NetworkCredential(user, pw)
                request.Method = WebRequestMethods.Ftp.GetFileSize

                Try
                    Dim response As FtpWebResponse = request.GetResponse()
                Catch ex As WebException
                    Dim response As FtpWebResponse = ex.Response
                    If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then
                        Return False
                    End If
                End Try
            End If
            Return True
        End If



    End Function

    Private Sub txtSuche_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSuche.KeyDown

        Dim sqladdon As String = ""


        If e.KeyCode = Keys.Enter Then
            If txtSuche.Text <> "" Then
                sqladdon &= " [api_program] Like '%" & txtSuche.Text & "%' or  [api_url] like '%" & txtSuche.Text & "%'"
            End If
            loadDGV(sqladdon)
        End If

    End Sub

    Private Sub cbxProduktivsystem_CheckedChanged(sender As Object, e As EventArgs) Handles cbxProduktivsystem.CheckedChanged
        Dim sqladdon As String = ""
        If txtSuche.Text <> "" Then
            sqladdon &= " [api_program] Like '%" & txtSuche.Text & "%' or  [api_url] like '%" & txtSuche.Text & "%'"
        End If
        loadDGV(sqladdon)

    End Sub

    Private Sub DataGridView_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView.CellDoubleClick
        Me.Cursor = Cursors.WaitCursor
        Dim tmprowindex As Integer = e.RowIndex
        If DataGridView.Columns(e.ColumnIndex).Name = "pathToFile" Then

            If DataGridView.CurrentRow.Cells("api_debugpath").Value <> "" Then
                Dim path As New System.IO.DirectoryInfo(DataGridView.CurrentRow.Cells("api_debugpath").Value)

                If DataGridView.CurrentRow.Cells("api_debugpath").Value IsNot DBNull.Value AndAlso path.Exists Then
                    Process.Start(DataGridView.CurrentRow.Cells("api_debugpath").Value)
                End If
            End If

        ElseIf DataGridView.Columns(e.ColumnIndex).Name = "api_program" Then
            If DataGridView.CurrentRow.Cells("api_program").Value <> "" AndAlso DataGridView.CurrentRow.Cells("api_program").Value.ToString.ToLower = "creditsafe" Then
                openCreditsafeRequests()
            End If


        End If
            Me.Cursor = Cursors.Default
    End Sub

    Private Sub PictureBox5_Click(sender As Object, e As EventArgs) Handles PictureBox5.Click
        Dim webAddress As String = "https://wiki.verag.ag/de/software/Offene_Punkte#aviso-schnittstellen-zu-fremdsystemen"
        Process.Start(webAddress)
    End Sub

    Private Sub openCreditsafeRequests()
        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim frm As New Form
            Dim dgv As New DataGridView()
            Dim dt As New DataTable
            Dim cs = New cCreditSafeAPI("creditsafe")
            cs.authenticate()
            cs.getSubscriptionCountries(dt)
            dgv.DataSource = dt
            If dgv IsNot Nothing Then
                frm.Size = New Size(1400, 1000)
                dgv.Size = New Size(frm.Size.Width - 50, frm.Size.Height - 50)
                dgv.Dock = DockStyle.Fill
                dgv.Anchor = AnchorStyles.Left
                dgv.Anchor = AnchorStyles.Top
                dgv.ReadOnly = True
                frm.Controls.Add(dgv)
                frm.StartPosition = FormStartPosition.CenterScreen
                frm.ShowDialog()
            End If


        Catch ex As System.Exception

            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try


    End Sub
End Class