' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Public Class FTP

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

    Public Sub CEPS_upload()
        Try

     
        If Main.config.CEPS.CEPS_dir_IN = "" Or Main.config.CEPS.CEPS_dir_OUT = "" Then Exit Sub
        Dim files_to_download As New List(Of String)
        Dim DIR_request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.CEPS.CEPS_dir_IN)
        DIR_request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
        DIR_request.Method = WebRequestMethods.Ftp.ListDirectory
        Dim response As FtpWebResponse = DIR_request.GetResponse()
        Dim responseStream As Stream = response.GetResponseStream
        Using reader As New StreamReader(responseStream)
            Do While reader.Peek <> -1
                Dim file = reader.ReadLine
                RichTextBox1.AppendText(file & vbCrLf)
                Application.DoEvents()
                If InStr(file, "CEPS_mensuel") = 1 Then
                    Dim download = False
                    If Main.config.CEPS.CEPS_MENSUEL = "" Then
                        download = True
                    ElseIf (CDbl(Mid(file, 14, 6)) > CDbl(Mid(Main.config.CEPS.CEPS_MENSUEL, 14, 6))) Then
                        download = True
                    End If
                    If download = True Then
                        files_to_download.Add(file)
                    End If

                ElseIf InStr(file, "CEPS_quotidien") = 1 Then
                    Dim download = False
                    If Main.config.CEPS.CEPS_Quotidien = "" Then
                        download = True
                    ElseIf (CDbl(Mid(file, 16, 8)) > CDbl(Mid(Main.config.CEPS.CEPS_Quotidien, 16, 8))) Then
                        download = True
                    End If
                    If download = True Then
                        files_to_download.Add(file)
                    End If
                End If
            Loop
            files_to_download.Sort()
            For r = 0 To files_to_download.Count - 1
                If FTPDownloadFile(Main.config.CEPS.CEPS_dir_OUT & "\" & files_to_download(r), "ftp://" & Main.config.FTP.Serveur & Main.config.CEPS.CEPS_dir_IN & "/" & _
                                    files_to_download(r), Main.config.FTP.user, Main.config.FTP.password) = True Then
                    If InStr(files_to_download(r), "CEPS_mensuel") = 1 Then
                        If Main.config.CEPS.CEPS_MENSUEL = "" Then
                            Main.config.update_config("CEPS", "CEPS_MENSUEL", files_to_download(r))
                        ElseIf (CDbl(Mid(files_to_download(r), 14, 6)) > CDbl(Mid(Main.config.CEPS.CEPS_MENSUEL, 14, 6))) Then
                            Main.config.update_config("CEPS", "CEPS_MENSUEL", files_to_download(r))
                        End If
                    ElseIf InStr(files_to_download(r), "CEPS_quotidien") = 1 Then
                        If Main.config.CEPS.CEPS_Quotidien = "" Then
                            Main.config.update_config("CEPS", "CEPS_Quotidien", files_to_download(r))
                        ElseIf (CDbl(Mid(files_to_download(r), 16, 8)) > CDbl(Mid(Main.config.CEPS.CEPS_Quotidien, 16, 8))) Then
                            Main.config.update_config("CEPS", "CEPS_Quotidien", files_to_download(r))
                        End If
                    End If
                End If
            Next
        End Using
            response.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try

    End Sub
    Private Sub FtpUploadFile(ByVal filetoupload As String, ByVal ftpuri As String, ByVal ftpusername As String, ByVal ftppassword As String)
        ' Create a web request that will be used to talk with the server and set the request method to upload a file by ftp.
        Dim ftpRequest As FtpWebRequest = CType(WebRequest.Create(ftpuri), FtpWebRequest)
        Try
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile

            ' Confirm the Network credentials based on the user name and password passed in.
            ftpRequest.Credentials = New NetworkCredential(ftpusername, ftppassword)

            ' Read into a Byte array the contents of the file to be uploaded 
            Dim bytes() As Byte = System.IO.File.ReadAllBytes(filetoupload)

            ' Transfer the byte array contents into the request stream, write and then close when done.
            ftpRequest.ContentLength = bytes.Length
            Using UploadStream As Stream = ftpRequest.GetRequestStream()
                UploadStream.Write(bytes, 0, bytes.Length)
                UploadStream.Close()
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Exit Sub
        End Try

        MessageBox.Show("Process Complete")
    End Sub

    Private Function FTPDownloadFile(ByVal downloadpath As String, ByVal ftpuri As String, ByVal ftpusername As String, ByVal ftppassword As String) As Boolean
        'Create a WebClient.
        Dim request As New WebClient()

        ' Confirm the Network credentials based on the user name and password passed in.
        request.Credentials = New NetworkCredential(ftpusername, ftppassword)

        'Read the file data into a Byte array
        Dim bytes() As Byte = request.DownloadData(ftpuri)

        Try
            '  Create a FileStream to read the file into
            Dim DownloadStream As FileStream = IO.File.Create(downloadpath)
            '  Stream this data into the file
            DownloadStream.Write(bytes, 0, bytes.Length)
            '  Close the FileStream
            DownloadStream.Close()

        Catch ex As Exception
            Main.log("failed: " & ftpuri & vbCrLf & ex.Message)
            Return False
        End Try
        Main.log("download: " & ftpuri)
        Return True
    End Function

    Public Sub LOI_upload()
        Try

     
        If Main.config.LOI.LOI_dir_IN = "" Or Main.config.LOI.LOI_dir_OUT = "" Then Exit Sub
        Dim files_to_download As New List(Of String)
        Dim DIR_request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.LOI.LOI_dir_IN)
        DIR_request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
        DIR_request.Method = WebRequestMethods.Ftp.ListDirectory
        Dim response As FtpWebResponse = DIR_request.GetResponse()
        Dim responseStream As Stream = response.GetResponseStream
        Using reader As New StreamReader(responseStream)
            Do While reader.Peek <> -1
                Dim file = reader.ReadLine
                If file <> "." And file <> ".." Then
                    files_to_download.Add(file)
                End If

            Loop
            files_to_download.Sort()
            Dim version_online = CDec(Mid(files_to_download(files_to_download.Count - 1), 1, InStr(files_to_download(files_to_download.Count - 1), ".") - 1))
            Dim download = False
            If Main.config.LOI.LOI_version = "" Then
                download = True
            ElseIf version_online > CDec(Main.config.LOI.LOI_version) Then
                download = True
            End If
            If download = True Then
                If FTPDownloadFile(Main.config.LOI.LOI_dir_OUT & "\" & files_to_download(files_to_download.Count - 1), "ftp://" & Main.config.FTP.Serveur & Main.config.LOI.LOI_dir_IN & "/" & _
                                    files_to_download(files_to_download.Count - 1), Main.config.FTP.user, Main.config.FTP.password) = True Then
                    If InStr(files_to_download(files_to_download.Count - 1), ".gz") <> 0 Then
                        ShellandWait("c:\gzip", "gzip.exe", "-d -q " & Main.config.LOI.LOI_dir_OUT & "\" & files_to_download(files_to_download.Count - 1))
                    End If
                    If My.Computer.FileSystem.FileExists(Main.config.LOI.LOI_dir_OUT & "\loi.loi") Then
                        My.Computer.FileSystem.DeleteFile(Main.config.LOI.LOI_dir_OUT & "\loi.loi")
                    End If
                    My.Computer.FileSystem.RenameFile(Main.config.LOI.LOI_dir_OUT & "\" & version_online.ToString & ".loi", "loi.loi")

                    Main.config.update_config("LOI", "LOI_version", version_online.ToString)
                End If
            End If



        End Using
            response.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub LPP_upload()
        Try


            If Main.config.LPP.LPP_dir_IN = "" Or Main.config.LPP.LPP_dir_OUT = "" Then Exit Sub
            Dim files_to_download As New List(Of String)
            Dim DIR_request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.LPP.LPP_dir_IN)
            DIR_request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
            DIR_request.Method = WebRequestMethods.Ftp.ListDirectory
            Dim response As FtpWebResponse = DIR_request.GetResponse()
            Dim responseStream As Stream = response.GetResponseStream
            Using reader As New StreamReader(responseStream)
                Do While reader.Peek <> -1
                    Dim file = reader.ReadLine
                    If file <> "." And file <> ".." Then
                        files_to_download.Add(file)
                    End If

                Loop
                files_to_download.Sort()
                Dim version_online = CDec(Mid(files_to_download(files_to_download.Count - 1), 7, InStr(files_to_download(files_to_download.Count - 1), ".") - 7))
                Dim download = False
                If Main.config.LPP.LPP_version = "" Then
                    download = True
                ElseIf version_online > CDec(Main.config.LPP.LPP_version) Then
                    download = True
                End If
                If download = True Then
                    If FTPDownloadFile(Main.config.LPP.LPP_dir_OUT & "\" & files_to_download(files_to_download.Count - 1), "ftp://" & Main.config.FTP.Serveur & Main.config.LPP.LPP_dir_IN & "/" & _
                                        files_to_download(files_to_download.Count - 1), Main.config.FTP.user, Main.config.FTP.password) = True Then
                        My.Computer.FileSystem.RenameFile(Main.config.LPP.LPP_dir_OUT & "\" & files_to_download(files_to_download.Count - 1), Mid(files_to_download(files_to_download.Count - 1), 1, InStr(files_to_download(files_to_download.Count - 1), ".")) & "gz")
                        ShellandWait("c:\gzip", "gzip.exe", "-d -q " & Main.config.LPP.LPP_dir_OUT & "\" & Mid(files_to_download(files_to_download.Count - 1), 1, InStr(files_to_download(files_to_download.Count - 1), ".")) & "gz")
                        Main.config.update_config("LPP", "LPP_version", version_online.ToString)
                    End If
                End If



            End Using
            response.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub ShellandWait(ByVal ProcessDirectory As String, ByVal ProcessName As String, ByVal arguments As String)
        Dim objProcess As System.Diagnostics.Process
        Try
            objProcess = New System.Diagnostics.Process()
            objProcess.StartInfo.FileName = ProcessName
            objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            'objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
            objProcess.StartInfo.Arguments = arguments
            objProcess.StartInfo.WorkingDirectory = ProcessDirectory
            objProcess.Start()

            'Wait until the process passes back an exit code 
            objProcess.WaitForExit()

            'Free resources associated with this process
            objProcess.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub officine_exe_upload()
        Try

  
        For Each p As Process In Process.GetProcesses
            If String.Compare(p.ProcessName, "pharma-gestion", True) = 0 Then
                Exit Sub
            End If
        Next
            Dim request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/officine.exe")
            request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp
            Dim response As FtpWebResponse = request.GetResponse
            Dim new_version = response.LastModified.ToString
            If new_version = Main.config.EXE.EXE_version Then Exit Sub


            If FTPDownloadFile(Main.config.EXE.EXE_dir_OUT & "\officine.exe", "ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/officine.exe", Main.config.FTP.user, Main.config.FTP.password) = True Then
                Main.config.update_config("EXE", "EXE_version", new_version)
            End If
            
            response.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub OfficineLib_dll__upload()
        Try


            For Each p As Process In Process.GetProcesses
                If String.Compare(p.ProcessName, "pharma-gestion", True) = 0 Then
                    Exit Sub
                End If
            Next
            Dim request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/OfficineLib.dll")
            request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp
            Dim response As FtpWebResponse = request.GetResponse
            Dim new_version = response.LastModified.ToString
            If new_version = Main.config.EXE.OfficineLib_version Then Exit Sub


            If FTPDownloadFile(Main.config.EXE.EXE_dir_OUT & "\OfficineLib.dll", "ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/OfficineLib.dll", Main.config.FTP.user, Main.config.FTP.password) = True Then
                Main.config.update_config("EXE", "OfficineLib_version", new_version)
            End If

            response.Close()
        Catch ex As Exception
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub Officine_ScriptSQL_upload()

        Try


            For Each p As Process In Process.GetProcesses
                If String.Compare(p.ProcessName, "pharma-gestion", True) = 0 Then
                    Exit Sub
                End If
            Next
            Dim request = FtpWebRequest.Create("ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/Officine.sql")
            request.Credentials = New NetworkCredential(Main.config.FTP.user, Main.config.FTP.password)
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp
            Dim response As FtpWebResponse = request.GetResponse


            If FTPDownloadFile(Application.StartupPath & "\Officine.sql", "ftp://" & Main.config.FTP.Serveur & Main.config.EXE.EXE_dir_IN & "/Officine.sql", Main.config.FTP.user, Main.config.FTP.password) = True Then
                Main.NotifyIcon1.Text = "Mise à jour base de données"
                System.Threading.Thread.Sleep(3000)
                Dim Process = New Process()
                Process.StartInfo.UseShellExecute = False
                Process.StartInfo.RedirectStandardOutput = True
                Process.StartInfo.RedirectStandardError = True
                Process.StartInfo.CreateNoWindow = True
                Process.StartInfo.FileName = "SQLCMD.EXE"
                Process.StartInfo.Arguments = "-S " & My.Computer.Name & "\SQLEXPRESS -i " & Application.StartupPath & "\Officine.sql -o out.log"
                Process.StartInfo.WorkingDirectory = Application.StartupPath
                Process.StartInfo.CreateNoWindow = True

                Process.Start()
                Process.WaitForExit()





            End If

            response.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
            Main.log("failed: " & vbCrLf & ex.Message)
        End Try
    End Sub
End Class