Imports System.Net
Imports System.Text.RegularExpressions
Imports uPLibrary.Networking.M2Mqtt

Public Class frmLogin

    ' TODO: 제공된 사용자 이름과 암호를 사용하여 사용자 지정 인증을 수행하는 코드를 삽입합니다
    ' (자세한 내용은 http://go.microsoft.com/fwlink/?LinkId=35339 참조).  
    ' 그러면 사용자 지정 보안 주체가 현재 스레드의 보안 주체에 다음과 같이 첨부될 수 있습니다. 
    '     My.User.CurrentPrincipal = CustomPrincipal
    ' 여기서 CustomPrincipal은 인증을 수행하는 데 사용되는 IPrincipal이 구현된 것입니다. 
    ' 나중에 My.User는 CustomPrincipal 개체에 캡슐화된 사용자 이름, 표시 이름 등의
    ' ID 정보를 반환합니다.
    Private FirstLogin As Boolean = False
    Private Const LocalHostIP As String = "192.168.0.250"
    Private Const IntServerHubDNS As String = "jomt.iptime.org"
    Private Const Ext_802_HubDNS As String = "jomt802.iptime.org"

    Private IntServerHubIPaddr As IPHostEntry = Dns.GetHostEntry(IntServerHubDNS)

    Public IntServerHubIP As String = IntServerHubIPaddr.AddressList(0).ToString
    Public Ext_DeviceIP As String
    Public mqttStart As Boolean = False

    Public Structure UserIDType
        Public UserID As String
        Public UserPW As String
        Public IDType As String
        Public ExtPermition As String
    End Structure
    Public UserInfo As UserIDType

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        UserInfo.UserID = ""
        UserInfo.UserPW = ""
        UserInfo.IDType = ""
        UserInfo.ExtPermition = ""

        Try
            StrCmd = "select UserPW,IDType,ExtPermition from jomtTesterUserIDTbl where UserID = '" & UsernameTextBox.Text & "';"
            If UserDBQueryReader(StrCmd) Then
                UserInfo.UserID = UsernameTextBox.Text
                UserInfo.UserPW = sqlDataQuery(0)
                UserInfo.IDType = sqlDataQuery(1)
                UserInfo.ExtPermition = sqlDataQuery(2)

                If PasswordTextBox.Text = UserInfo.UserPW Then

                    If mqttStart = False Then
                        If mqttConnect() Then
                            GoTo loginsuccess
                        Else
                            GoTo mqttfail
                        End If
                    Else
                        GoTo loginsuccess
                    End If

                End If
            Else
                GoTo loginfail
            End If
        Catch ex As Exception
            MsgBox("DUALSONIC Software Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + ", " + Err.Description, vbExclamation, "DUALSONIC Manager")
            Me.Close()
        End Try

mqttfail:
        Exit Sub

loginfail:
        PasswordTextBox.Text = ""
        MsgBox("아이디 및 비밀번호를 확인하세요!", vbExclamation, "DUALSONIC Manager")
        frmTD_JIG.EnableSetup = False
        Exit Sub
loginsuccess:
        Try
            PasswordTextBox.Text = ""
            If FirstLogin = True Then
                FirstLogin = False
                frmTD_JIG.Show()
            Else
                frmTD_JIG.EnableSetup = True
                frmTD_JIG.Show()
                frmTD_JIG.runSetupWindow()
            End If
            Me.Hide()
        Catch ex As Exception
            MsgBox("DUALSONIC Software Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + ", " + Err.Description, vbExclamation, "DUALSONIC Manager")
        End Try
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
        If FirstLogin = True Then
            Me.Close()
        Else
            Me.Hide()
        End If
    End Sub

    Private Sub frmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim TmpHubIP As String
        Try
            If FirstLogin = True Then

                TmpHubIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
                TmpHubIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(TmpHubIP)(0).ToString()
                Ext_DeviceIP = TmpHubIP.ToString

                If Ext_DeviceIP = IntServerHubIP Then

                    If mqttStart = False Then
                        If frmMqtt.loadMqtt = False Then
                            frmMqtt.txbMqttAd.Text = String.Empty
                            frmMqtt.txbMqttTp.Text = String.Empty
                            frmTD_JIG.mqttBroker = String.Empty
                            frmTD_JIG.mqttTopic = String.Empty
                            mqttStart = False
                        Else
                            mqttStart = True
                        End If
                    End If

                Else
                    MsgBox("허용된 장소가 아니므로 프로그램을 종료합니다!", vbExclamation, "DUALSONIC Manager")
                    Me.Close()
                End If
            Else
                If mqttStart = False Then
                    If frmMqtt.loadMqtt = False Then
                        frmMqtt.txbMqttAd.Text = String.Empty
                        frmMqtt.txbMqttTp.Text = String.Empty
                        frmTD_JIG.mqttBroker = String.Empty
                        frmTD_JIG.mqttTopic = String.Empty

                        mqttStart = False
                    Else
                        If mqttConnect() Then
                            mqttStart = True
                        Else
                            mqttStart = False
                        End If
                    End If
                End If
            End If

            UsernameTextBox.Focus()

        Catch ex As Exception
            MsgBox("DUALSONIC Software Error: " + vbCrLf + CStr(Err.Number) + ", " + Err.Source + ", " + Err.Description, vbExclamation, "DUALSONIC Manager")
            Me.Close()
        End Try
    End Sub

    Public Function mqttConnect() As Boolean
        Try
            If frmTD_JIG.mqttBroker = String.Empty Or frmTD_JIG.mqttTopic = String.Empty Then
                MsgBox("MQTT 브로커 혹은 토픽을 알 수 없습니다." & vbCrLf & "설정하여 주십시오.", vbExclamation)
                Return False
            End If

            frmTD_JIG.MQTClient = New MqttClient(frmTD_JIG.mqttBroker)
            Dim ClientID As String = Guid.NewGuid.ToString

            frmTD_JIG.MQTClient.Connect(ClientID)

            If frmTD_JIG.MQTClient.IsConnected = True Then
                Return True
            Else
                MsgBox("존재하지 않는 Broker 명입니다. 확인해 주십시오.", vbCritical)
                Return False
            End If

        Catch ex As Exception
            MsgBox("오류 발생 :: " & ex.Message.ToString, vbCritical)
            Return False
        End Try
    End Function

    Private Sub PictureBox1_DoubleClick(sender As Object, e As EventArgs) Handles PictureBox1.DoubleClick
        frmMqtt.ShowDialog()
    End Sub
End Class
