Imports System.IO.File
Imports System.Net.Mail
Imports Renci.SshNet
Imports System.IO

Public Class Form1

    Public sAppPath As String = Application.StartupPath
    Public parameter As String() = Environment.GetCommandLineArgs.ToArray()
    Public PDFUploadPath As String = ""

    Public DatumNextMonday As String
    Public DatumThisWeeksMonday As String
    Public Silent As Boolean = False

    Public Shared HighwayFTPUser As String = "u78672691"
    Public Shared HighwayFTPPwd As String = "LmZAK6x!Ur6^7BaUkCV^5Zk*G"
    Public Shared HighwayFTPSrv As String = "home546285429.1and1-data.host"

    Private Function LoadParameters()
        Try
            Dim lines = IO.File.ReadAllLines(sAppPath.Substring(0, sAppPath.Length - 10) & "\start.ini")
            Dim colCount = lines.First.Split(";"c).Length

            For Each line In lines
                Dim objFields = From field In line.Split(";"c)

                Select Case objFields(0).ToString
                    Case "PDFUploadPath"
                        PDFUploadPath = objFields(1).ToString
                End Select

            Next
        Catch ex As Exception
            MsgBox("FTPUpload: start.ini nicht gefunden!")
        End Try

    End Function

    Public Function Upload()
        If Silent = True Then
            DoUpload()
        Else
            If MsgBox("Achtung! Mit Bestätigen dieser Meldung wird das aktuelle Mittagsmenü auf der Homepage ÜBERSCHRIEBEN!", MsgBoxStyle.OkCancel, "Upload") = MsgBoxResult.Ok Then
                DoUpload()

            Else
                Exit Function
            End If
        End If
    End Function

    Function DoUpload()
        Dim anhang, anhangdateiname As String

        If Exists(PDFUploadPath & DatumNextMonday & ".pdf") Then
            anhang = PDFUploadPath & DatumNextMonday & ".pdf"
            anhangdateiname = DatumNextMonday & ".pdf"
        Else
            If Silent = False Then
                MsgBox("Datei nicht gefunden. Bitte erst erstellen.") : Exit Function
            Else
                sendMail("FTP Upload fehlgeschlagen!", "Der automatische Upload wurde nicht ausgeführt. Datei: " & PDFUploadPath & DatumNextMonday & ".pdf wurde nicht gefunden.") : Exit Function
            End If
        End If

        Upload2SFTP(HighwayFTPSrv, 22, HighwayFTPUser, HighwayFTPPwd, anhang)
    End Function


    Public Function GetNextMonday()
        Dim datum As Date = Now.Date.AddDays(7)

        For i = 0 To 10
            If datum.DayOfWeek = 1 Then
                Exit For
            Else
                datum = datum.AddDays(-1)
            End If
        Next
        DatumNextMonday = datum.Date.ToString.Substring(0, 10)
        Return (DatumNextMonday)
    End Function

    Public Function GetThisWeeksMonday()
        Dim datum As Date = Now.Date.AddDays(0)

        For i = 0 To 10
            If datum.DayOfWeek = 1 Then
                Exit For
            Else
                datum = datum.AddDays(-1)
            End If
        Next
        DatumThisWeeksMonday = datum.Date.ToString.Substring(0, 10)
        Return (DatumThisWeeksMonday)
    End Function


    Public Function Upload2SFTP(server As String, port As Integer, user As String, pwd As String, filePath As String, Optional Silent As Boolean = False) As Boolean
        Try
            ' Verbindung zu SFTP herstellen
            Using sftpClient As New SftpClient(server, port, user, pwd)
                sftpClient.Connect()

                ' Datei einlesen
                Dim fileBytes() As Byte = File.ReadAllBytes(filePath)
                Dim remoteFileName As String = "/speisekarte/Mittagsmenue.pdf" 'Path.GetFileName(filePath)

                ' Datei hochladen
                Using stream As New MemoryStream(fileBytes)
                    sftpClient.UploadFile(stream, remoteFileName)
                End Using

                sftpClient.Disconnect()
            End Using

            ' Rückmeldung und optional E-Mail
            If Not Silent Then
                MsgBox("Upload erfolgreich abgeschlossen.")
            End If
            sendMail("SFTP-Upload ausgeführt", $"Der automatische Upload wurde ausgeführt. Datei: {filePath}")

            Return True
        Catch ex As Exception
            ' Fehlerbehandlung
            MsgBox("Fehler beim SFTP-Upload: " & ex.Message)
            Return False
        End Try
    End Function

    Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
        GetNextMonday()
        Upload()
    End Sub

    Private Sub bntUploadAndClose_Click(sender As Object, e As EventArgs) Handles bntUploadAndClose.Click
        GetNextMonday()
        Upload()
        Close()
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadParameters()


        For i = 0 To parameter.Length - 1
            Select Case parameter(i).ToString
                Case "/auto"
                    ' MsgBox("p")
                    Silent = True
                    bntUploadAndClose.PerformClick()
                Case "/sql"
                    Silent = True
                    sqlsendinator()
            End Select
        Next


    End Sub

    Public Function sqlsendinator()
        Gastro.cListe.selectDBConnection("SQLGuide01")
        Dim sql As New Gastro.cSQL

        Dim Upload2SQLGuide As String = "INSERT INTO [SQLGUIDE01.verag.ost.dmn].[AVISO].dbo.[tblEBMenu]
Select *, 4 as [MenuBestellungBisTageVorher] from [192.168.2.17].[Gastro].dbo.[GMenu] as table1
WHERE NOT EXISTS (
    select * from [SQLGUIDE01.verag.ost.dmn].[AVISO].dbo.[tblEBMenu] as table2 WHERE table1.MenuTitel = table2.MenuTitel AND table1.[MenuDateVon] = table2.[MenuDateVon]
)
"

        sql.SqlQuery(Upload2SQLGuide)

        Close()

    End Function

    Public Function sendMail(subject As String, body As String)
        Try
            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential("monitoring@verag.com", "Ju18WA10")
            Smtp_Server.Port = 25
            Smtp_Server.EnableSsl = False
            Smtp_Server.Host = "owa.verag.ag"

            e_mail = New MailMessage()
            e_mail.From = New MailAddress("monitoring@verag.com")
            e_mail.To.Add("monitoring@verag.com")
            ' e_mail.Subject = "FTP Upload ausgeführt"
            e_mail.Subject = subject
            e_mail.IsBodyHtml = False
            'e_mail.Body = "Der automatische Upload wurde ausgeführt. Datei: " & PDFUploadPath & DatumNextMonday & ".pdf"
            e_mail.Body = body
            Smtp_Server.Send(e_mail)
            If Silent = False Then MsgBox("Mail Sent")

        Catch error_t As Exception
            MsgBox(error_t.ToString)
        End Try
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        sqlsendinator()

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        GetThisWeeksMonday()
        DatumNextMonday = DatumThisWeeksMonday
        Upload()
    End Sub
End Class
