Imports System.Threading
Imports System.Text

Public Class Form_AZ_EL
    Dim AP_AL As String
    Dim ALdeg, ALmin, ALsec As String
    Dim ALsign As String
    Dim AP_AZ As String
    Dim Resp As String
    Dim AZdeg, AZmin, AZsec As String
    Dim GoodValue As Boolean = True
    Dim tickBegin As Long
    Dim tickEnd As Long
    Public Status As String

    Protected Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            Const CS_DBLCLKS As Int32 = &H8
            Const CS_NOCLOSE As Int32 = &H200
            cp.ClassStyle = CS_DBLCLKS Or CS_NOCLOSE
            Return cp
        End Get
    End Property


    Private Sub ButtonClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonClose.Click
        Me.Hide()

    End Sub

    Private Sub ButtonGetRD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGetRD.Click
        If Form1.SerialPort1.IsOpen = True Or Form1.SocketIsOpen = True Or Form1.IsConnected = True Then
            GetScopeAzEl()
            AP_AL = Form1.AP_AL
            AP_AZ = Form1.AP_AZ
            If AP_AL = "" Then
                ToolStripStatusLabel.Text = "No response"
            Else
                Try
                    If AP_AL.Length >= 10 Then
                        ALsign = Mid(AP_AL, 1, 1)
                        ALdeg = Mid(AP_AL, 2, 2)
                        ALmin = Mid(AP_AL, 5, 2)
                        ALsec = Mid(AP_AL, 8, 2)
                        LabelAlt.Text = ALsign & ALdeg & "° " & ALmin & "' " & ALsec & """  Altitude"
                        If ALsign = "+" Then
                            ALplus.Checked = True
                        Else
                            ALminus.Checked = True
                        End If
                        ALd.Value = ALdeg
                        ALm.Value = ALmin
                        ALs.Value = ALsec
                    Else
                        LabelAlt.Text = "Invalid Altitude "
                    End If

                    If AP_AZ = "" Then
                        ToolStripStatusLabel.Text = "No response"
                        Form_Dome.TrackBarScope.Value = ToolStripStatusLabel.Text
                    Else
                        Dim StartDeg As Integer
                        Dim StartMin As Integer
                        Dim StartSec As Integer
                        StartDeg = InStr(AP_AZ, "+")
                        StartMin = InStr(AP_AZ, "*")
                        StartSec = StartMin + 3
                        AZdeg = Mid(AP_AZ, StartDeg + 1, StartMin - StartDeg - 1)
                        AZmin = Mid(AP_AZ, StartMin + 1, 2)
                        AZsec = Mid(AP_AZ, StartSec + 1, 2)
                        GoodValue = True

                        If GoodValue = True Then
                            LabelAz.Text = AZdeg & "° " & AZmin & "' " & AZsec & """  Azimuth"
                            AZd.Value = AZdeg
                            AZm.Value = AZmin
                            AZs.Value = AZsec

                            GetMeridianDist()
                            LabelMer.Text = Form1.AP_MeridianDist

                            Form1.UpdateStatusLine("Get Alt/Az successful", Color.Black)
                            If Form_Monitor.Visible = True Then
                                Form1.Update_Scope_Pos()
                            End If
                        Else
                            LabelAz.Text = "Invalid Azimuth"
                        End If
                        Form_Dome.TrackBarScope.Value = AZdeg
                        ToolStripStatusLabel.Text = AP_AL & "  " & AP_AZ
                    End If

                Catch ex As Exception
                    If Form1.ErrorMsgBox = True Then
                        Dim M As String
                        M = ex.Message & vbCrLf & "AL = " & AP_AL & vbCrLf & "AZ = " & AP_AZ
                        MsgBox(M, MsgBoxStyle.OkOnly, "Get Alt/Az Error")
                    End If
                    ToolStripStatusLabel.Text = "Invalid response: " & AP_AL & " " & AP_AZ
                    Form1.UpdateStatusLine("Get Alt/Az failed", Color.DarkRed)
                End Try

            End If

        Else
            ToolStripStatusLabel.Text = "Not connteced"
        End If

    End Sub


    Private Sub ButtonGotoRD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGotoRD.Click
        Dim ALsign As String
        Dim MountTrackingStop As String = " ,tracking stopped"
        Dim MT As String = ""

        If Form1.SerialPort1.IsOpen = True Or Form1.SocketIsOpen = True Or Form1.IsConnected = True Then
            If Form1.StopOnAltAzSlew = True Then
                MT = MountTrackingStop
                Form1.AP_Command("TrackingStop")
            End If

            If ALplus.Checked = True Then
                ALsign = "+"
            Else
                ALsign = "-"
            End If
            AP_AL = ":Sa " & ALsign & Format(ALd.Value, "00") & "*" _
                    & Format(ALm.Value, "00") & ":" _
                    & Format(ALs.Value, "00") & "#"

            AP_AZ = ":Sz " & Format(AZd.Value, "000") & "*" _
                    & Format(AZm.Value, "00") & ":" _
                    & Format(AZs.Value, "00") & "#"

            Status = ""
            Resp = ""

            If Form1.AscomConnect = True Then
                SendReceiveAP(AP_AL, "Goto AL", True, 1)
                SendReceiveAP(AP_AZ, "Goto AZ", True, 1)
                SendReceiveAP(":MS#", "Slew", True, 1)
                Form1.UpdateStatusLine("Goto Alt/Az successful", Color.Black)
                Status = "Successful."
            Else
                If Form1.APnetwork = False Then
                    ' serial port connection to AP mount
                    Try
                        Form1.SerialPort1.Write(AP_AL & AP_AZ)
                        Form1.LogScope("Sent > ", Color.DarkBlue, AP_AL & AP_AZ)

                        tickBegin = Int(Date.Now.Ticks / 10000000)
                        Do Until Resp.Length >= 2
                            Resp = Resp & Form1.SerialPort1.ReadExisting()
                            tickEnd = Int(Date.Now.Ticks / 10000000)
                            If tickEnd - tickBegin > Form1.ReadTimeout Then
                                Status = "Timeout sending Alt/Az"
                                Exit Do
                            End If
                        Loop
                        Form1.LogScope("Resp < ", Color.DarkGreen, Resp)
                        Form1.Rsp = Resp

                        If Resp = "11" Then
                            Resp = ""
                            Form1.SerialPort1.Write(":MS#")
                            Form1.LogScope("Sent > ", Color.DarkBlue, ":MS#")
                            tickBegin = Int(Date.Now.Ticks / 10000000)
                            Do Until Resp.Length >= 1
                                Resp = Resp & Form1.SerialPort1.ReadExisting()
                                tickEnd = Int(Date.Now.Ticks / 10000000)
                                If tickEnd - tickBegin > Form1.ReadTimeout Then
                                    Status = "Timeout sending slew"
                                    Exit Do
                                End If
                            Loop
                            Form1.LogScope("Resp < ", Color.DarkGreen, Resp)
                            Form1.Rsp = Resp
                            If Resp = "0" Then
                                Status = "Successful."
                                Form1.UpdateStatusLine("Goto Alt/Az successful" & MT, Color.Black)
                            End If
                        End If

                        ToolStripStatusLabel.Text = Status
                    Catch ex As Exception
                        If Form1.ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "AL = " & AP_AL & vbCrLf & "AZ = " & AP_AZ
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto Alt/Az Error")
                        End If
                        Form1.UpdateStatusLine("Goto Alt/Az failed", Color.DarkRed)
                    End Try

                Else
                    ' network connection to AP mount
                    Try
                        Dim ApRec(50) As Byte
                        Dim Cmd As String = AP_AL & AP_AZ
                        ApRec = Encoding.ASCII.GetBytes(Cmd)
                        Form1.networkStream.Write(ApRec, 0, Cmd.Length)
                        Form1.LogScope("Sent > ", Color.DarkBlue, AP_AL & AP_AZ)

                        Dim TermChr As String = "11"
                        Dim TermChrLen As Integer = 2
                        Dim RespLen As Integer = 1
                        If Form1.CP4ip = True Then
                            TermChr = "1" & Chr(10) & "1" & Chr(10)
                            TermChrLen = 4
                            RespLen = 2
                        End If

                        Do
                            Form1.NumBytesRead = Form1.networkStream.Read(Form1.MountRec, 0, Form1.MountRec.Length)
                            Resp = Resp & Encoding.ASCII.GetString(Form1.MountRec, 0, Form1.NumBytesRead)
                        Loop Until Microsoft.VisualBasic.Right(Resp, TermChrLen) = TermChr

                        Resp = Resp.Replace(Chr(10), "")
                        Form1.LogScope("Resp > ", Color.DarkGreen, Resp)
                        Form1.Rsp = Resp

                        If Resp = "11" Then
                            Resp = ""
                            Dim Cmd2 As String = ":MS#"
                            ApRec = Encoding.ASCII.GetBytes(Cmd2)
                            Form1.networkStream.Write(ApRec, 0, Cmd2.Length)
                            Form1.LogScope("Sent > ", Color.DarkBlue, Cmd2)

                            Do
                                Form1.NumBytesRead = Form1.networkStream.Read(Form1.MountRec, 0, Form1.MountRec.Length)
                                Resp = Resp & Encoding.ASCII.GetString(Form1.MountRec, 0, Form1.NumBytesRead)
                            Loop Until Resp.Length = RespLen

                            Resp = Resp.Replace(Chr(10), "")
                            Form1.LogScope("Resp > ", Color.DarkGreen, Resp)
                            Form1.Rsp = Resp
                            If Resp = "0" Then
                                If Form1.StopOnAltAzSlew = True Then
                                    MT = MountTrackingStop
                                    Form1.AP_Command("TrackingStop")
                                End If
                                Status = "Successful."
                                Form1.UpdateStatusLine("Goto Alt/Az successful" & MT, Color.Black)
                            End If
                        End If
                    Catch ex As Exception
                        If Form1.ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "AL = " & AP_AL & vbCrLf & "AZ = " & AP_AZ
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto Alt/Az Error")
                        End If
                        Form1.UpdateStatusLine("Goto Alt/Az failed", Color.DarkRed)
                    End Try

                End If

            End If

            ToolStripStatusLabel.Text = Status
        Else
            ToolStripStatusLabel.Text = "Not connected"
        End If

    End Sub

    Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonStop.Click
        Form1.ButtonSlewStop.PerformClick()

    End Sub

    Private Sub Form_AZ_EL_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Make sure form is on the screen
        If Me.Location.X < 0 Or Me.Location.Y < 0 Then
            Me.Location = New Point(0, 0)
        End If

        ' Make sure window is not off of screen
        If Me.Left + Me.Width > Form1.ScreenWidth Then
            Me.Left = Form1.ScreenWidth - Me.Width - 100
        End If
        If Me.Top + Me.Height > Form1.ScreenHeight Then
            Me.Top = Form1.ScreenHeight - Me.Height - 100
        End If

    End Sub

    Private Sub ButtonSetPark4_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetPark4.Click
        Dim ALsign As String

        If ALplus.Checked = True Then
            ALsign = "+"
        Else
            ALsign = "-"
        End If
        Form1.AP_AL_Park4 = ":Sa " & ALsign & Format(ALd.Value, "00") & "*" _
                & Format(ALm.Value, "00") & ":" _
                & Format(ALs.Value, "00") & "#"

        Form1.AP_AZ_Park4 = ":Sz " & Format(AZd.Value, "000") & "*" _
                & Format(AZm.Value, "00") & ":" _
                & Format(AZs.Value, "00") & "#"

        Dim AL As String = Mid(Form1.AP_AL_Park4, 5, 9)
        Dim AZ As String = Mid(Form1.AP_AZ_Park4, 5, 9)

        ToolStripStatusLabel.Text = "Position Park4 set "
        Form1.UpdateStatusLine(ToolStripStatusLabel.Text & "Alt=" & AL & ", Az=" & AZ, Color.Black)
        Dim P4tip As String = "Altitude " & AL & vbCrLf & "Azimuth " & AZ
        Form1.Position4ToolStripMenuItem.Text = "Position 4" & vbCrLf & P4tip
        Form_ControlP.CheckBoxPark4.Text = "Park4  (Alt:" & AL & "  Az:" & AZ & ")"

    End Sub

    Private Sub ButtonClearPark4_Click(sender As System.Object, e As System.EventArgs) Handles ButtonClearPark4.Click
        ToolStripStatusLabel.Text = "Position Park4 cleared"
        Form1.UpdateStatusLine(ToolStripStatusLabel.Text, Color.Black)
        Form1.AP_AL_Park4 = ""
        Form1.AP_AZ_Park4 = ""
        Form1.Position4ToolStripMenuItem.Text = "Position 4" & vbCrLf & "Not set"

    End Sub
End Class