Module Utils_UsefulFunctions

    Friend Function FormatSeconds(ByVal seconds As Double) As String
        If seconds >= 3600 Then
            Return Date.FromOADate(seconds / 86400).ToString("hh:mm:ss")
        ElseIf seconds >= 60 Then
            Return Date.FromOADate(seconds / 86400).ToString("mm:ss")
        Else
            Return CInt(seconds).ToString
        End If
    End Function

    ' ===================================================================================
    '  ConvertFTP_ToArubaHTTP
    ' ===================================================================================
    ' FROM: ftp://www.freetw.net/freetw.net/downloads/Backup_Livio/
    '   TO: http://www.freetw.net/downloads/Backup_Livio/
    ' -----------------------------------------------------------------
    ' FROM: ftp://www.theremino.com/www.theremino.com/files/
    '   TO: http://www.www.theremino.com/files/
    ' -----------------------------------------------------------------
    Friend Function ConvertFTP_ToArubaHTTP(ByVal ftp As String) As String
        If String.IsNullOrEmpty(ftp) Then Return ""

        ' Remove ftp://
        Dim path As String = ftp
        If path.StartsWith("ftp://") Then
            path = path.Substring(6)
        End If

        ' Find the first slash after the hostname
        Dim firstSlash As Integer = path.IndexOf("/")
        If firstSlash <= 0 Then Return ""

        ' Extract the hostname and the rest of the path
        Dim hostname As String = path.Substring(0, firstSlash)
        Dim restPath As String = path.Substring(firstSlash + 1)

        ' If there is no website folder (we are at the root level), return empty
        ' Example: ftp.theremino.com/  -> nothing to convert
        If String.IsNullOrEmpty(restPath) Then
            Return ""
        End If

        ' Check if the first folder is a website (starts with "www.") or just a folder
        Dim secondSlash As Integer = restPath.IndexOf("/")
        Dim websiteFolder As String
        Dim remainingPath As String

        If secondSlash <= 0 Then
            ' Only one folder in the path
            websiteFolder = restPath
            remainingPath = ""
        Else
            websiteFolder = restPath.Substring(0, secondSlash)
            remainingPath = restPath.Substring(secondSlash + 1)
        End If

        ' If the folder doesn't look like a website (starts with "www."), it's probably
        ' a backup folder or other non-website content. Return empty or the folder name.
        If Not websiteFolder.StartsWith("www.") Then
            ' It could be a backup folder like "backup_livio" or "uploads"
            ' In this case, we can't determine the HTTP URL
            Return ""
        End If

        ' Build the HTTP URL using the website folder as the hostname
        Return "https://" & websiteFolder & "/" & remainingPath
    End Function


    ' ===================================================================================
    '  RemoveLastFolderFromUrl
    ' ===================================================================================
    Friend Function RemoveLastFolderFromUrl(ByVal url As String) As String
        If Right(url, 1) = "/" Then
            url = url.Remove(url.Length - 1)
        End If

        Dim i As Int32 = InStrRev(url, "/")
        If i > 0 Then
            Return url.Remove(i)
        Else
            Return url
        End If
    End Function


    ' ===================================================================================
    '  GET DROP DESTINATION PATH 
    ' ===================================================================================
    Friend Function Get_DropDestinationPath() As String
        '
        Dim hwnd As Int32 = GetWindowUnderTheCursor()
        '
        If hwnd = Get_DesktopListView_Handle() Then

            'Debug.Print(Get_CursorPointedIcon_Info())

            ' -------------------------------------------------------- the handle is the Desktop
            If Get_CursorPointedIcon_Info() <> "" Then
                ' ---------------------------------------------------- the cursor is over a icon ( invalid destination ) 
                Return ""
            Else
                ' ---------------------------------------------------- the cursor is on the desktop
                Return GetDesktopPath()
            End If

        Else
            ' -------------------------------------------------------- the handle is a explorer window
            Return GetWindowsExplorerPath(hwnd)
        End If
    End Function


    ' ===================================================================================
    '  Get_DesktopListView_Handle 
    ' ===================================================================================

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
                                                                      ByVal lpWindowName As String) As Int32

    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWndParent As Int32, _
                                                                              ByVal hWndChildAfter As Integer, _
                                                                              ByVal lpClassName As String, _
                                                                              ByVal lpWindowName As String) As Int32
    Private Function Get_DesktopListView_Handle() As Int32
        Dim lHandle As Int32
        lHandle = FindWindow("Progman", vbNullString)
        lHandle = FindWindowEx(lHandle, 0, "SHELLDLL_defVIEW", vbNullString)
        Return FindWindowEx(lHandle, 0, "SysListView32", vbNullString)
    End Function


    Friend Function GetDesktopPath() As String
        Return Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\"
    End Function


    ' ===================================================================================
    '  GetWindowsExplorerPath 
    ' ===================================================================================

    Private Declare Function GetParent Lib "user32" (ByVal hwnd As Int32) As Int32
    '
    ' --------------------------------------------------------------------------
    ' import the Com library "Microsoft Internet Controls" into the project
    ' --------------------------------------------------------------------------
    Private Function GetWindowsExplorerPath(ByVal hWnd As Int32) As String
        '
        For Each ie As SHDocVw.InternetExplorer In New SHDocVw.ShellWindowsClass
            '
            Dim testHwnd As Int32 = hWnd
            Do
                If ie.HWND = testHwnd Then
                    Dim filename As String
                    filename = IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower
                    If filename.Equals("explorer") Then
                        Dim url As String = ie.LocationURL
                        url = Strings.Mid(url, 6)
                        url = url.Replace("/", "\")
                        If url.StartsWith("\\\") Then url = Strings.Mid(url, 4)
                        url = url.Replace("%20", " ")
                        Return url & "\"
                    Else
                        Return ""
                    End If
                Else
                    testHwnd = GetParent(testHwnd)
                End If
            Loop Until testHwnd = 0
        Next
        Return ""
    End Function



    ' ===================================================================================
    '  GetWindowUnderTheCursor
    ' ===================================================================================

    Private Declare Function WindowFromPoint Lib "user32" (ByVal x As Int32, ByVal y As Int32) As Int32
    '
    Private Function GetWindowUnderTheCursor() As Int32
        Return WindowFromPoint(Cursor.Position.X, Cursor.Position.Y)
    End Function


    ' ===================================================================================
    '  ASYNC KEY STATE
    ' ===================================================================================

    Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Int32) As Int16

    Private Const PRESSED_NOW As Int32 = &H8000
    Private Const PRESSED_AFTER_PREVIOUS_CALL As Int32 = &H1

    Public Function Key(ByVal k As Int32) As Boolean
        Key = (GetAsyncKeyState(k) And PRESSED_NOW) <> 0
    End Function

    Public Function KeyPrevious(ByVal k As Int32) As Boolean
        KeyPrevious = (GetAsyncKeyState(k) And PRESSED_AFTER_PREVIOUS_CALL) <> 0
    End Function

    Public Sub WaitMouseOff()
        While Key(Keys.LButton) Or Key(Keys.MButton) Or Key(Keys.RButton)
            SleepMyThread(1)
        End While
    End Sub

    Public Sub WaitKeyOff(ByVal WaitKey As Int32)
        Do
            SleepMyThread(1)
        Loop Until Not Key(WaitKey)
    End Sub


    ' ===================================================================================
    '  SLEEP MY THREAD
    ' ===================================================================================
    Public Sub SleepMyThread(ByVal TimeMillisec As Int32)
        System.Threading.Thread.Sleep(TimeMillisec)
    End Sub


    ' ===================================================================================
    '  FINAL BEEP
    ' ===================================================================================
    Friend Sub FinalBeep()
        My.Computer.Audio.Play(My.Resources.FadeOut, AudioPlayMode.Background)
    End Sub


    ' ===================================================================================
    '   FtpPathToRelative - Convert FTP URL to relative path for FTP server
    '   Example: ftp://ftp.theremino.com/www.theremino.com/... -> /www.theremino.com/...
    ' ===================================================================================
    Friend Function FtpPathToRelative(ByVal ftpPath As String) As String
        If String.IsNullOrEmpty(ftpPath) Then Return ftpPath

        ' If it starts with ftp://, remove protocol and hostname
        If ftpPath.StartsWith("ftp://") Then
            Dim pathWithoutProtocol As String = ftpPath.Substring(6) ' Remove "ftp://"
            Dim firstSlash As Integer = pathWithoutProtocol.IndexOf("/")
            If firstSlash > 0 Then
                ' Remove hostname (e.g. "ftp.theremino.com")
                Return pathWithoutProtocol.Substring(firstSlash)
            End If
        End If

        Return ftpPath
    End Function

End Module
