Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.Encoding

Public Class TCPComm
    Public IsClosing As Boolean = False
    Public _Clientf As New tcpCommClient(AddressOf UpdateUI)
    Dim WithEvents Client As ArOZ_Network.Client
    Dim autoclose As Boolean = False
    Dim TargetID As String = ""
    Dim nextfile As Boolean = True
    Dim nextdir As String = ""

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '//initate and gte ip address
        Dim arc As New ArConfig
        Dim al As String = Application.StartupPath & "\config\"
        TextBox8.Text = arc.ReadConfig(al, "tcpcommip").ToString.Trim
        TextBox2.Text = arc.ReadConfig(al, "name")

        Client = New ArOZ_Network.Client()
        Dim ID As String = TextBox2.Text
        Dim IP As String = TextBox8.Text
        Client.Connect(IP, 1010, ID) 'Text transfer with Port 1010

        _Clientf.Connect(Me.TextBox8.Text.Trim, 1011)
    End Sub
    Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Client.Disconnect()
        _Clientf.StopRunning()
    End Sub
    Private Sub Connected() Handles Client.Connected
        On Error Resume Next
        TextBox4.AppendText("Connected!" & vbNewLine)

    End Sub
    Private Sub Disconnected() Handles Client.Disconnected
        On Error Resume Next
        TextBox4.AppendText("Lost connection!" & vbNewLine)
    End Sub
    Private Sub errHandler(ByVal ex As Exception) Handles Client.errEncounter
        MsgBox(ex.Message)
    End Sub
    Private Sub DataReceived(ByVal Data() As Byte, ByVal ID As String) Handles Client.DataReceived
        If ID = Nothing Then ID = "Host"
        Dim Msg As String = Client.ConvertFromAscii(Data)
        balloon.DisplayText(Client.ConvertFromAscii(Data))
        TextBox4.AppendText(ID & ": " & Msg & vbNewLine)
        If autoclose = True Then
            Me.Close()
        End If
    End Sub
    Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Client.SendData(Client.Convert2Ascii(TextBox1.Text), TargetID)
        TextBox1.Text = ""
        TextBox1.Focus()


    End Sub
    Public Sub AutoPopUp()
        Me.Show()
        autoclose = True
    End Sub
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TargetID = InputBox("Enter the client ID you wish to send him information, leave blank to send the data to the host", "Please write down the client ID you wish to send the data to")
    End Sub

    '///////////////////frm Client System for File transfer//////////
    Private Function BytesToString(ByVal data() As Byte) As String
        Dim enc As New System.Text.UTF8Encoding()
        BytesToString = enc.GetString(data)
    End Function

    Private Function StrToByteArray(ByVal text As String) As Byte()
        Dim encoding As New System.Text.UTF8Encoding()
        StrToByteArray = encoding.GetBytes(text)
    End Function

    Public Sub UpdateUI(ByVal bytes() As Byte, ByVal dataChannel As Integer)

        If Me.InvokeRequired() Then
            ' InvokeRequired: We're running on the background thread. Invoke the delegate.
            Me.Invoke(_Clientf.ClientCallbackObject, bytes, dataChannel)
        Else
            ' We're on the main UI thread now.
            Dim dontReport As Boolean = False

            If dataChannel < 251 Then
                TextBox4.AppendText(BytesToString(bytes))
            ElseIf dataChannel = 255 Then
                Dim msg As String = BytesToString(bytes)
                Dim tmp As String = ""

                ' Display info about the incoming file:
                If msg.Length > 15 Then tmp = msg.Substring(0, 15)
                If tmp = "Receiving file:" Then
                    TextBox4.AppendText("Receiving: " & _Clientf.GetIncomingFileName & vbNewLine)
                    dontReport = True
                End If

                ' Display info about the outgoing file:
                If msg.Length > 13 Then tmp = msg.Substring(0, 13)
                If tmp = "Sending file:" Then
                    TextBox4.AppendText("Sending: " & _Clientf.GetOutgoingFileName & vbNewLine)
                    dontReport = True
                End If

                ' The file being sent to the client is complete.
                If msg = "->Done" Then
                    TextBox4.AppendText("File->Client: Transfer complete." & vbNewLine)
                    Button4.Text = "Get File"
                    dontReport = True
                End If

                ' The file being sent to the server is complete.
                If msg = "<-Done" Then
                    TextBox4.AppendText("File->Server: Transfer complete." & vbNewLine)
                    Button3.Text = "Send File"
                    nextfile = True
                    dontReport = True
                End If

                ' The file transfer to the client has been aborted.
                If msg = "->Aborted." Then
                    TextBox4.AppendText("File->Client: Transfer aborted." & vbNewLine)
                    dontReport = True
                End If

                ' The file transfer to the server has been aborted.
                If msg = "<-Aborted." Then
                    TextBox4.AppendText("File->Server: Transfer aborted." & vbNewLine)
                    dontReport = True
                End If

                ' _Clientf as finished sending the bytes you put into sendBytes()
                If msg.Length > 4 Then tmp = msg.Substring(0, 4)
                If tmp = "UBS:" Then ' User Bytes Sent on channel:???.
                    ' btSendText.Enabled = True
                    dontReport = True
                End If

                ' We have an error message. Could be local, or from the server.
                If msg.Length > 4 Then tmp = msg.Substring(0, 5)
                If tmp = "ERR: " Then
                    Dim msgParts() As String
                    msgParts = Split(msg, ": ")
                    MsgBox("" & msgParts(1), MsgBoxStyle.Critical, "ERROR")
                    dontReport = True
                End If

                ' Display all other messages in the status strip.
                ' If Not dontReport Then Me.ToolStripStatusLabel1.Text = BytesToString(bytes)
                ' End If
            End If
        End If
    End Sub

    Private Sub frmClient_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        IsClosing = True
        _Clientf.StopRunning()
        While _Clientf.isClientRunning
            Application.DoEvents()
        End While
    End Sub

    Private Sub frmClient_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        IsClosing = True
        _Clientf.StopRunning()
        While _Clientf.isClientRunning
            Application.DoEvents()
        End While
    End Sub

    Private Sub frmClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox3.Text = _Clientf.GetLocalIpAddress.ToString
        _Clientf.SetReceivedFilesFolder(Application.StartupPath & "downloads")
        tmrPoll.Start()
    End Sub





    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If Button4.Text = "Get File" Then
            Dim filedir() As String = TextBox7.Text.Split("|")
            Dim dir As String
            For Each dir In filedir
                If dir <> Nothing Then
                    TextBox5.Text = dir
                    Button4.Text = "Cancel"
                    If _Clientf.isClientRunning Then _Clientf.GetFile(TextBox5.Text.Trim)
                    Threading.Thread.Sleep(200)
                    Do Until Button4.Text = "Get File"
                        Application.DoEvents()
                    Loop
                    Threading.Thread.Sleep(200)
                    TextBox7.Text = TextBox7.Text.Replace(TextBox6.Text, Nothing)

                End If
            Next
        Else
            _Clientf.CancelIncomingFileTransfer()
            Button4.Text = "Get File"
        End If
        balloon.DisplayText("接收完成了。")
        Me.Close()
    End Sub

    Private Sub tmrPoll_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrPoll.Tick
        ' Update progress bars
        ProgressBar1.Value = _Clientf.GetPercentOfFileReceived
        ProgressBar2.Value = _Clientf.GetPercentOfFileSent

        ' Update Mbps
        Me.Text = "ArOZ Omega TCP Communication Control Panel (" & _Clientf.GetMbps & ")"

        'Update BackgroundWorker
        Label4.Text = _Clientf.GetPercentOfFileSent & _Clientf.isClientRunning
    End Sub


    Private Sub btSendFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If Button3.Text = "Send File" Then
            Dim filedir() As String = TextBox7.Text.Split("|")
            Dim dir As String
            For Each dir In filedir
                If dir <> Nothing Then
                    TextBox6.Text = dir
                    Button3.Text = "Sending"
                    SendFile()
                    Threading.Thread.Sleep(200)
                    Do Until Button3.Text = "Send File"
                        Application.DoEvents()
                    Loop

                    Threading.Thread.Sleep(200)
                    TextBox7.Text = TextBox7.Text.Replace(TextBox6.Text, Nothing)

                End If
            Next

        Else
            _Clientf.CancelOutgoingFileTransfer()
            Button3.Text = "Send File"
        End If
        balloon.DisplayText("傳送完成了。")
        Me.Close()
    End Sub

    Public Sub SendFilesToServer()
        If Button3.Text = "Send File" Then
            Dim filedir() As String = TextBox7.Text.Split("|")
            Dim dir As String
            For Each dir In filedir
                If dir <> Nothing Then
                    TextBox6.Text = dir
                    Button3.Text = "Sending"
                    SendFile()
                    Threading.Thread.Sleep(200)
                    Do Until Button3.Text = "Send File"
                        Application.DoEvents()
                    Loop

                    Threading.Thread.Sleep(200)
                    TextBox7.Text = TextBox7.Text.Replace(TextBox6.Text, Nothing)

                End If
            Next

        Else
            _Clientf.CancelOutgoingFileTransfer()
            Button3.Text = "Send File"
        End If
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        DropPanel.Show()
    End Sub

    Private Sub SendFile()
        If _Clientf.isClientRunning Then _Clientf.SendFile(TextBox6.Text.Replace(vbNewLine, ""))
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        IsClosing = True
        Client.Disconnect()
        _Clientf.StopRunning()
        While _Clientf.isClientRunning
            Application.DoEvents()
        End While
        Client = New ArOZ_Network.Client()
        Dim ID As String = TextBox2.Text
        Dim IP As String = TextBox8.Text
        Client.Connect(IP, 1010, ID) 'Text transfer with Port 1010

        _Clientf.Connect(Me.TextBox8.Text.Trim, 1011)
    End Sub

    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            Client.SendData(Client.Convert2Ascii(TextBox1.Text), TargetID)
            TextBox1.Text = ""
            TextBox1.Focus()
            TextBox1.Text = Nothing
        End If

    End Sub
End Class