Imports System.Threading
Imports System.IO
Imports System.Text

Public Class Form_RA_DEC
    Public AP_DEC As String
    Public AP_RA As String
    Dim AP_AL As String
    Dim AP_AZ As String
    Dim GoodValue As Boolean = True
    Dim Resp As String
    Dim Coor() As String
    Dim tickBegin As Long
    Dim tickEnd As Long
    Public Status As String
    Dim CoordFile 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


    Public Sub ButtonGetRD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGetRD.Click
        Dim I As Integer
        Dim AZ_Value As String
        Dim TelescopeSt As String

        If Form1.SerialPort1.IsOpen = True Or Form1.SocketIsOpen = True Or Form1.IsConnected = True Then
            GetScopeRaDec()
            AP_RA = Form1.AP_RA
            AP_DEC = Form1.AP_DEC
            TelescopeSt = Form1.TelescopeST
            LabelST.Text = TelescopeSt & " ST"
            LabelSide.Text = Form1.TelescopeSide
            If AP_RA = "" Then
                ToolStripStatusLabel.Text = "No response"
            Else
                ToolStripStatusLabel.Text = AP_DEC & "  " & AP_RA
                Try
                    RAh.Value = Mid(AP_RA, 1, 2)
                    RAm.Value = Mid(AP_RA, 4, 2)
                    RAs.Value = Mid(AP_RA, 7, 2)
                    RAss.Value = Mid(AP_RA, 10, 1)
                    If Mid(AP_DEC, 1, 1) = "+" Then
                        DECplus.Checked = True
                    Else
                        DECminus.Checked = True
                    End If
                    DECd.Value = Mid(AP_DEC, 2, 2)
                    DECm.Value = Mid(AP_DEC, 5, 2)
                    DECs.Value = Mid(AP_DEC, 8, 2)

                    Form1.RAtext = Mid(AP_RA, 1, 2) & "h " & _
                             Mid(AP_RA, 4, 2) & "m " & _
                             Mid(AP_RA, 7, 2) & "." & _
                             Mid(AP_RA, 10, 1) & "s"
                    Form1.DECtext = Mid(AP_DEC, 1, 1) & _
                              Mid(AP_DEC, 2, 2) & "° " & _
                              Mid(AP_DEC, 5, 2) & "' " & _
                              Mid(AP_DEC, 8, 2) & """"

                    GetScopeAzEl()
                    AP_AL = Form1.AP_AL
                    AP_AZ = Form1.AP_AZ

                    LabelAlt.Text = Mid(AP_AL, 1, 3) & "° Altitude"
                    I = InStr(AP_AZ, "*") - 2
                    If I > 0 Then
                        AZ_Value = Mid(AP_AZ, 2, I)
                        LabelAz.Text = AZ_Value & "° Azimuth"
                        Form_Dome.TrackBarScope.Value = AZ_Value
                    Else
                        LabelAz.Text = "Unknown"
                    End If

                    GetMeridianDist()
                    LabelMer.Text = Form1.AP_MeridianDist

                    Form1.UpdateStatusLine("Get RA/DEC successful", Color.Black)

                    If Form_Monitor.Visible = True Then
                        Form1.Update_Scope_Pos()
                    End If
                Catch ex As Exception
                    If Form1.ErrorMsgBox = True Then
                        Dim M As String
                        M = ex.Message & vbCrLf & "RA = " & AP_RA & vbCrLf & "DEC = " & AP_DEC
                        MsgBox(M, MsgBoxStyle.OkOnly, "Get RA/DEC Error")
                    End If
                    ToolStripStatusLabel.Text = "Invalid response: " & AP_RA & " " & AP_DEC
                    Form1.UpdateStatusLine("Get RA/DEC failed", Color.DarkRed)
                End Try
            End If
        Else
            ToolStripStatusLabel.Text = "Not connected"
        End If


    End Sub

    Private Sub ButtonGotoRD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonGotoRD.Click
        AP_RA = ":Sr " & Format(RAh.Value, "00") & ":" _
                & Format(RAm.Value, "00") & ":" _
                & Format(RAs.Value, "00") & "." _
                & Format(RAss.Value, "0") & "#"
        If DECplus.Checked = True Then
            AP_DEC = ":Sd +"
        Else
            AP_DEC = ":Sd -"
        End If
        AP_DEC = AP_DEC & Format(DECd.Value, "00") & "*" _
                & Format(DECm.Value, "00") & ":" _
                & Format(DECs.Value, "00") & "#"

        GotoRaDec()

    End Sub

    Public Sub GotoRaDec()
        If Form1.SerialPort1.IsOpen = True Or Form1.SocketIsOpen = True Or Form1.IsConnected = True Then
            Status = ""
            Form1.RAtext = ""
            Form1.DECtext = ""
            Resp = ""
            If Form1.AscomConnect = True Then
                SendReceiveAP(AP_RA, "Goto RA", True, 1)
                SendReceiveAP(AP_DEC, "Goto DEC", True, 1)
                SendReceiveAP(":MS#", "Slew", True, 1)
                Form1.UpdateStatusLine("Goto RA/DEC successful", Color.Black)
                Status = "Successful."
            Else
                If Form1.APnetwork = False Then
                    ' serial port connection to AP mount
                    Try
                        Form1.SerialPort1.Write(AP_RA & AP_DEC)
                        Form1.LogScope("Sent > ", Color.DarkBlue, AP_RA & AP_DEC)
                        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 RA/DEC"
                                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
                                Form1.UpdateStatusLine("Goto RA/DEC successful", Color.Black)
                                Status = "Successful."
                                Form1.RAtext = Mid(AP_RA, 5, 2) & "h " & _
                                               Mid(AP_RA, 8, 2) & "m " & _
                                               Mid(AP_RA, 11, 4) & "s"
                                Form1.DECtext = Mid(AP_DEC, 5, 1) & _
                                          Mid(AP_DEC, 6, 2) & "° " & _
                                          Mid(AP_DEC, 9, 2) & "' " & _
                                          Mid(AP_DEC, 12, 2) & """"
                            End If
                        End If
                    Catch ex As Exception
                        If Form1.ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "RA = " & AP_RA & vbCrLf & "DEC = " & AP_DEC
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto RA/DEC Error")
                        End If
                        Form1.UpdateStatusLine("Goto RA/DEC failed", Color.DarkRed)
                    End Try

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

                        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
                                Form1.UpdateStatusLine("Goto RA/DEC successful", Color.Black)
                                Status = "Successful."
                                Form1.RAtext = Mid(AP_RA, 5, 2) & "h " & _
                                               Mid(AP_RA, 8, 2) & "m " & _
                                               Mid(AP_RA, 11, 4) & "s"
                                Form1.DECtext = Mid(AP_DEC, 5, 1) & _
                                          Mid(AP_DEC, 6, 2) & "° " & _
                                          Mid(AP_DEC, 9, 2) & "' " & _
                                          Mid(AP_DEC, 12, 2) & """"
                            End If
                        End If
                    Catch ex As Exception
                        If Form1.ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "RA = " & AP_RA & vbCrLf & "DEC = " & AP_DEC
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto RA/DEC Error")
                        End If
                        Form1.UpdateStatusLine("Goto RA/DEC failed", Color.DarkRed)
                    End Try

                End If

            End If

            ToolStripStatusLabel.Text = Status
        Else
            Form1.UpdateStatusLine("Not connected", Color.DarkRed)

        End If

    End Sub

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

    End Sub

    Private Sub LabelAz_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelAz.Click
        ToolStripStatusLabel.Text = "Az received: " & AP_AZ

    End Sub

    Private Sub LabelAlt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelAlt.Click
        ToolStripStatusLabel.Text = "Alt received: " & AP_AL

    End Sub

    Private Sub Form_RA_DEC_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Form1.PosTopRD = Me.Top
        Form1.PosLeftRD = Me.Left

    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 ButtonRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRestore.Click
        Dim Rec As String = ""
        Dim Fields() As String

        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            CoordFile = OpenFileDialog1.FileName

            Try
                Using sr As StreamReader = New System.IO.StreamReader(CoordFile, System.Text.Encoding.Default)
                    Do Until sr.EndOfStream = True
                        ' HH MM SS.S + DD MM SS
                        Rec = sr.ReadLine
                        Fields = Split(Rec, " ")
                        If UBound(Fields) = 6 Then
                            RAh.Value = Fields(0)
                            RAm.Value = Fields(1)
                            RAs.Value = Mid(Fields(2), 1, 2)
                            RAss.Value = Mid(Fields(2), 4, 1)
                            If Fields(3) = "-" Then
                                DECminus.Checked = True
                            Else
                                DECplus.Checked = True
                            End If
                            DECd.Value = Fields(4)
                            DECm.Value = Fields(5)
                            DECs.Value = Fields(6)
                            ToolStripStatusLabel.Text = "RA/DEC set from file"
                            Form1.UpdateStatusLine("RA/DEC set from file: " & CoordFile, Color.Black)
                        Else
                            ToolStripStatusLabel.Text = "Restore Error"
                            Form1.UpdateStatusLine("Invalid format: " & Rec, Color.DarkRed)
                        End If
                    Loop
                    sr.Close()

                End Using

            Catch ex As Exception
                Form1.UpdateStatusLine("Restore Error: " & ex.Message, Color.DarkRed)
            End Try

        End If

    End Sub

    Private Sub ButtonSaveAS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSaveAS.Click
        Dim sw As StreamWriter = Nothing
        Dim Rec As String = ""

        SaveFileDialog1.FileName = CoordFile
        SaveFileDialog1.Filter = "RA/DEC file txt|*.txt;"
        If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            CoordFile = SaveFileDialog1.FileName

            Try
                sw = New System.IO.StreamWriter(CoordFile, False, System.Text.Encoding.UTF8)
                Rec = Rec & RAh.Value & " " & RAm.Value & " " & RAs.Value & "." & RAss.Value & " "
                If DECplus.Checked = True Then
                    Rec = Rec & "+ "
                Else
                    Rec = Rec & "- "
                End If
                Rec = Rec & DECd.Value & " " & DECm.Value & " " & DECs.Value
                sw.WriteLine(Rec)
                sw.Close()
                ToolStripStatusLabel.Text = "RA/DEC saved to file"
                Form1.UpdateStatusLine("Saved RA/DEC to: " & CoordFile, Color.Black)

            Catch ex As Exception
                ToolStripStatusLabel.Text = "Save Error"
                Form1.UpdateStatusLine("Save Error: " & ex.Message, Color.DarkRed)
            End Try

        End If

    End Sub

    Private Sub Form_RA_DEC_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 ButtonSave1_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSave1.Click
        Form1.SaveRD1()
        ButtonGoto1.Enabled = True

    End Sub

    Private Sub ButtonSave2_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSave2.Click
        Form1.SaveRD2()
        ButtonGoto2.Enabled = True

    End Sub

    Private Sub ButtonGoto1_Click(sender As System.Object, e As System.EventArgs) Handles ButtonGoto1.Click
        Form1.GotoRD1()

    End Sub

    Private Sub ButtonGoto2_Click(sender As System.Object, e As System.EventArgs) Handles ButtonGoto2.Click
        Form1.GotoRD2()

    End Sub

End Class