Imports Microsoft.Win32
Imports System.IO
Imports System.Net.NetworkInformation
Imports System.Net
Imports System.Net.Dns
Imports System.net.Mail
Imports System.Windows.Forms

Public Class ARINCLASS
    Structure s_userinfo
        Dim uid As Short
        Dim id As String
        Dim pass As String
        Dim name As String
        Dim tel As String
        Dim email As String
    End Structure


    Public Shared Sub SaveLoad_FrmSetting(ByVal Frm As Form, Optional ByVal Save As Boolean = False, Optional ByVal RestoreStatus As Boolean = False)
        '//폼의 상태를 저장합니다.
        'If Frm.FormBorderStyle <> FormBorderStyle.Sizable AndAlso Frm.FormBorderStyle <> FormBorderStyle.SizableToolWindow Then Return

        Dim Width As Short
        Dim Height As Short
        Dim State As Short
        Dim Left, Top As Short
        If Save Then
            Dim INI As New MyINI(My.Application.Info.DirectoryPath & "\Frm_Setting.ini")
            INI.Write(Frm.Name, "state", Frm.WindowState)
            INI.Write(Frm.Name, "width", Frm.Width)
            INI.Write(Frm.Name, "height", Frm.Height)
            INI.Write(Frm.Name, "left", Frm.Left)
            INI.Write(Frm.Name, "top", Frm.Top)
        Else
            Dim INI As New MyINI(My.Application.Info.DirectoryPath & "\Frm_Setting.ini")
            If Frm.WindowState = FormWindowState.Normal Then
                Width = INI.Read(Frm.Name, "width", 0)
                Height = INI.Read(Frm.Name, "height", 0)
                State = INI.Read(Frm.Name, "state", -1)
                Left = INI.Read(Frm.Name, "left", 0)
                Top = INI.Read(Frm.Name, "top", 0)
                If Width <> 0 Then Frm.Width = Width
                If Height <> 0 Then Frm.Height = Height
                If RestoreStatus Then If State <> -1 Then Frm.WindowState = State
                If Left <> 0 Then Frm.Left = Left
                If Top <> 0 Then Frm.Top = Top
            End If
        End If
    End Sub


    Private Function GetMacAddr() As String  '//MAC주소를 볼수있다.
        Dim computerProperties As IPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties()
        Dim nics As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
        Dim 출력용 As String = vbNullString
        Dim 카드타입 As String = vbNullString
        Dim 맥주소 As String = vbNullString
        Dim 임시맥주소 As String = vbNullString

        For Each Adp As NetworkInterface In nics
            카드타입 = Adp.NetworkInterfaceType.ToString.ToUpper.Trim
            맥주소 = Adp.GetPhysicalAddress.ToString.ToUpper.Trim
            If 카드타입 = "ETHERNET" Then
                If 임시맥주소 = "" Then
                    임시맥주소 = 맥주소
                End If
                If 임시맥주소 <> "" AndAlso 임시맥주소.Substring(0, 11) <> "005056C0000" Then
                    출력용 = 임시맥주소
                End If
            End If
        Next

        If 출력용 = vbNullString And 맥주소 = vbNullString Then
            Return "UNKNOWN"
        ElseIf 출력용 <> vbNullString Then
            Return (출력용)
        Else
            Return (임시맥주소)
        End If
    End Function 'DisplayTypeAndAddress

    Public Function GetLocalHostIP() As String  '//ip주소보기
        Dim objAddress() As IPAddress
        Dim IA As IPAddress
        Dim B(15) As Byte
        Dim sAns As String = vbNullString
        Try
            objAddress = Dns.GetHostEntry(GetHostName).AddressList

            For Each IA In objAddress   '//모든 ip를 테스트한다.리얼아이피를 찾는다.
                If IA.ToString.IndexOf(":") = -1 AndAlso IA.ToString.Substring(0, 3) <> "192" AndAlso _
                IA.ToString.Substring(0, 3) <> "168" AndAlso _
                IA.ToString.Substring(0, 3) <> "127" Then
                    sAns = IA.ToString
                End If
            Next
            If sAns = vbNullString Then
                For Each IA In objAddress   '//모든 ip를 테스트한다.리얼아이피를 찾는다.
                    If IA.ToString.IndexOf(":") = -1 Then
                        sAns = IA.ToString
                        Exit For
                    End If
                Next
            End If
        Catch ex As Exception
            sAns = vbNullString
        End Try
        Return sAns
    End Function

    Public Shared Function OpenFile(Optional ByVal IniFile As String = "", Optional ByVal ExtFilter As String = "모든파일|*.*") As String
        Dim OD As New OpenFileDialog
        'OD.InitialDirectory = IIf(IniFile = "", My.Application.Info.DirectoryPath, INitdir)
        OD.FileName = IniFile
        OD.Filter = ExtFilter
        OD.FilterIndex = 0

        If OD.ShowDialog <> DialogResult.OK Then
            Return ""
        Else
            Return OD.FileName
        End If
    End Function

    Public Shared Sub NOTICE(ByVal MSG As String, ByVal Src As Object)
        On Error Resume Next
        If Src.GetType.Name.ToUpper = "TOOLSTRIPSTATUSLABEL" Then
            CType(Src, Windows.Forms.ToolStripStatusLabel).Text = "▶ " & MSG & Space(1)
        ElseIf Src.GetType.Name.ToUpper = "LABEL" Then
            CType(Src, Windows.Forms.Label).Text = "▶ " & MSG & Space(1)
        End If
    End Sub
    Public Shared Sub NOTICE(ByVal MSG As String, ByVal FCOLOR As Drawing.Color, ByVal Src As Windows.Forms.ToolStripStatusLabel)
        Src.Text = "▶ " & MSG & Space(1)
        Src.ForeColor = FCOLOR
    End Sub
    Public Shared Sub NOTICE(ByVal MSG As String, ByVal Src As Windows.Forms.ToolStripStatusLabel, ByVal FCOLOR As Drawing.Color)
        Src.Text = "▶ " & MSG & Space(1) & "[" & Format(Now, "HH시mm분ss초") & "]"
        Src.ForeColor = FCOLOR
        If FCOLOR = Drawing.Color.Red Then My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
    End Sub


    ''' <summary>
    ''' 폼을 표시합니다.
    ''' </summary>
    ''' <param name="fForm"></param>
    ''' <param name="MdiMainForm"></param>
    ''' <param name="MODALFORM"></param>
    ''' <param name="Fstate"></param>
    ''' <remarks></remarks>
    Public Shared Sub ShowForm(ByVal fForm As System.Windows.Forms.Form, ByVal MdiMainForm As System.Windows.Forms.Form, Optional ByVal MODALFORM As Boolean = False, Optional ByVal Fstate As System.Windows.Forms.FormWindowState = System.Windows.Forms.FormWindowState.Normal)
        Dim objForms As System.Windows.Forms.Form
        Dim ALREADY As Boolean = False

        If MdiMainForm Is Nothing Then
            If MODALFORM Then
                fForm.ShowDialog()
            Else
                fForm.Show()
            End If
            fForm.Activate()
            Return
        End If

        Try
            For Each objForms In MdiMainForm.MdiChildren
                If objForms.Name = fForm.Name Then
                    ALREADY = True
                    'fForm.Dispose()
                    'fForm = Nothing
                    objForms.Focus()
                    Return
                End If
            Next
        Catch ex As Exception

        End Try

        If ALREADY = False Then
            With fForm
                If MdiMainForm Is Nothing Then
                    MsgBox("MDI 부모폼이 존재하지않습니다", MsgBoxStyle.Critical, "error")
                Else
                    If Not MdiMainForm Is Nothing Then
                        .MdiParent = MdiMainForm
                        '.StartPosition = FormStartPosition.CenterParent
                    End If
                    .WindowState = Fstate
                    If MODALFORM Then
                        .ShowDialog()
                    Else
                        .Show()
                    End If
                End If
            End With
        End If
    End Sub

    ''' <summary>
    ''' 동일한 프로세스가 존재하는지 확인합니다.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function PrevInstance() As Boolean
        If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
            Return True
        Else
            Return False
        End If
    End Function


    ''' <summary>
    ''' 메세지박스입니다. 내부메세지중 \n 과 \N 을 줄바꿈으로 처리합니다
    ''' </summary>
    ''' <param name="prompt"></param>
    ''' <param name="but"></param>
    ''' <param name="title"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function MSG(ByVal prompt As Object, Optional ByVal but As Microsoft.VisualBasic.MsgBoxStyle = MsgBoxStyle.OkOnly, Optional ByVal title As Object = Nothing) As MsgBoxResult
        prompt = prompt.ToString.Replace("\n", vbCrLf)
        prompt = prompt.ToString.Replace("\N", vbCrLf)
        Return MsgBox(prompt, but, title)
    End Function

    Public Function SendErrMaili(ByVal msg As String, ByVal type As String, ByVal info As Arintool.UserINfo) As Boolean

        Try
            Dim mailobj As New MailMessage
            Dim A As New Text.StringBuilder
            A.AppendLine("===============")
            A.AppendLine("USER:" & info.Name)
            A.AppendLine("IP:" & info.IP)
            A.AppendLine("MAC:" & info.Mac)
            A.AppendLine("LEVEL:" & info.Level)
            A.AppendLine("Date:" & info.OverDate)

            mailobj = New MailMessage("tinsky82.cafe24.com", "deviltin@xt.to")
            mailobj.Body = msg & vbCrLf & A.ToString
            mailobj.Subject = "◆ 처리되지않은예외 ◆ : " & type
            mailobj.IsBodyHtml = True

            If type.ToUpper = "GSFEDITOR" Then PrepareAttach(mailobj) '//이게에러나면 스트럭쳐폴더를 보낸다.

            Dim c As New SmtpClient("mail.xtto.net")
            c.Send(mailobj)

            Return True
        Catch ex As Exception
            'MsgBox(ex.Message.ToString)
            Return False
        End Try

    End Function
    Private Function PrepareAttach(ByVal Obj As MailMessage) As Boolean
        Try
            Dim A As New DirectoryInfo(My.Application.Info.DirectoryPath & "\structure")
            Dim NMA As Net.Mail.Attachment
            Dim FI As FileInfo()
            Dim FIS As FileInfo
            If A.Exists = False Then Return False
            FI = A.GetFiles("*.*")
            For Each FIS In FI
                If FIS.Exists Then
                    'MsgBox(FIS.FullName)
                    NMA = New Net.Mail.Attachment(FIS.FullName)
                    Obj.Attachments.Add(NMA)
                End If
            Next
            Return True
        Catch
            Return False
        End Try

    End Function
    Public Function GetRealScriptPath(ByVal OrgPath As String) As String
        Dim Aran As New MyPath
        Dim RealPath As String = OrgPath.ToUpper

        If (RealPath.IndexOf("[APP]")) > -1 Then
            RealPath = RealPath.Replace("[APP]", My.Application.Info.DirectoryPath)
        ElseIf (RealPath.IndexOf("[SYSTEM]")) > -1 Then
            RealPath = RealPath.Replace("[SYSTEM]", Aran.System32)
        ElseIf (RealPath.IndexOf("[DESKTOP]")) > -1 Then
            RealPath = RealPath.Replace("[DESKTOP]", Aran.DesktopPath)
        ElseIf (RealPath.IndexOf("[MYDOCUMENT]")) > -1 Then
            RealPath = RealPath.Replace("[MYDOCUMENT]", Aran.Mydocument)
        ElseIf (RealPath.IndexOf("[WINDOWS]")) > -1 Then
            RealPath = RealPath.Replace("[WINDOWS]", Aran.Windows)
        End If

        Return RealPath
    End Function
    Public Sub WLog(ByVal msg As String, ByVal fname As String)
        '//로그를 기록합니다.
        Dim FD As String = My.Application.Info.DirectoryPath & "\LOG"
        If Not Directory.Exists(FD) Then Directory.CreateDirectory(FD)
        Dim FS As FileStream = New FileStream(FD & fname, FileMode.Append)
        Dim SW As StreamWriter = New StreamWriter(FS, System.Text.Encoding.Default)
        SW.WriteLine(Now.TimeOfDay.ToString & ":" & msg)
        SW.Flush()
        SW.Close()
        FS.Close()
    End Sub
    Public Sub WLog2(ByVal enable As Boolean, ByVal msg As String, ByVal fname As String)
        '//로그를 기록합니다.
        If Not enable Then Return
        Dim FD As String = My.Application.Info.DirectoryPath & "\LOG"
        If Not Directory.Exists(FD) Then Directory.CreateDirectory(FD)
        Dim FS As FileStream = New FileStream(FD & fname, FileMode.Append)
        Dim SW As StreamWriter = New StreamWriter(FS, System.Text.Encoding.Default)
        SW.WriteLine(Now.TimeOfDay.ToString & ":" & msg)
        SW.Flush()
        SW.Close()
        FS.Close()
    End Sub
    Shared Sub Log(ByVal msg As String)
        '//로그를 기록합니다.
        Dim FD As String = My.Application.Info.DirectoryPath & "\LOG"
        If Not Directory.Exists(FD) Then Directory.CreateDirectory(FD)
        Dim FS As FileStream = New FileStream(FD & "\log.txt", FileMode.Append)
        Dim SW As StreamWriter = New StreamWriter(FS, System.Text.Encoding.Default)
        SW.WriteLine(Now.TimeOfDay.ToString & ":" & msg)
        SW.Flush()
        SW.Close()
        FS.Close()
    End Sub

    Public Function TextEnc(ByVal SrcText As String) As String
        If SrcText = "" Then Return ""

        Dim Ec As New System.Text.UnicodeEncoding
        Dim Msg1 As New System.Text.StringBuilder
        For Each bi As Byte In Ec.GetBytes(SrcText)
            Msg1.Append(bi.ToString & ",")
        Next
        Msg1.Remove(Msg1.Length - 1, 1)
        Return Msg1.ToString
    End Function
    Public Function TextDec(ByVal srctext As String) As String
        Dim Ec As New System.Text.UnicodeEncoding
        Dim Z(srctext.Split(",").GetUpperBound(0)) As Byte
        Dim i As Int16 = 0
        For Each aa As String In srctext.ToString.Split(",")
            Z(i) = CType(aa, Byte)
            i += 1
        Next
        Return Ec.GetString(Z)
    End Function

    Public Sub Run_MyScript(ByVal ScriptFile As String)
        Dim strtemp As String = New String(Chr(0), 200) 'ini파일의 임시 변수
        If Not File.Exists(ScriptFile) Then Exit Sub

        Dim FS As FileStream = New FileStream(ScriptFile, FileMode.Open)
        Dim SR As StreamReader = New StreamReader(FS)

        While SR.Peek > -1
            Parse_MyScript(SR.ReadLine)
        End While
        SR.Close()
        FS.Close()

        File.Delete(ScriptFile)
    End Sub
    Private Sub Parse_MyScript(ByVal SCript As String)
        Dim 임시버퍼() As String = SCript.Split("/")
        Dim 임시문자열버퍼(3) As String
        Dim PARAM1 As String = vbNullString
        Dim PARAM2 As String = vbNullString
        Dim PARAM3 As String = vbNullString
        Dim PARAM4 As String = vbNullString
        Dim J As Short
        Dim Aran As New MyReG
        Dim AranPrc As New MyProcess

        Select Case 임시버퍼(0).ToUpper
            Case "MBOX"
                For J = 0 To Len(임시버퍼(1)) - 1
                    임시문자열버퍼(0) = IIf(임시버퍼(1).Substring(J, 1) <> "\", 임시문자열버퍼(0) & 임시버퍼(1).Substring(J, 1), 임시문자열버퍼(0) & vbCrLf)
                Next J
                MsgBox(임시문자열버퍼(0), MsgBoxStyle.Information, "알림")

            Case "RUN" '//파일실행 스크립트(완료)
                PARAM1 = GetRealScriptPath(임시버퍼(1))
                If Not AranPrc.RunProcess(PARAM1) Then
                    'MsgBox("실행할 파일이 존재하지 않습니다", MsgBoxStyle.Critical, "스크립트실패")
                Else
                    AranPrc.RunProcess(PARAM1)
                End If

            Case "COPY" '//파일복사(완료)

                PARAM1 = GetRealScriptPath(임시버퍼(1))
                PARAM2 = GetRealScriptPath(임시버퍼(2))

                If Not File.Exists(PARAM1) Then
                    'MsgBox("복사할PARAM1이 존재하지 않습니다", MsgBoxStyle.Critical, "스크립트실패")

                Else
                    File.Copy(PARAM1, PARAM2, True)
                End If

            Case "DEL" '//파일삭제(완료)
                PARAM1 = GetRealScriptPath(임시버퍼(1))

                If Not File.Exists(PARAM1) Then
                    'MsgBox("삭제할 파일이 존재하지않습니다", MsgBoxStyle.Critical, "스크립트실패")
                Else
                    File.Delete(PARAM1)
                End If

            Case "MOVE" '//파일이동
                PARAM1 = GetRealScriptPath(임시버퍼(1))
                PARAM2 = GetRealScriptPath(임시버퍼(2))

                If File.Exists(PARAM2) Then File.Delete(PARAM2) '//대상파일이 있으면 삭제한다.

                If File.Exists(PARAM1) Then
                    File.Move(PARAM1, PARAM2)
                End If

            Case "REGWRITE"
                PARAM1 = (임시버퍼(1))
                PARAM2 = (임시버퍼(2))
                PARAM3 = (임시버퍼(3))
                PARAM4 = (임시버퍼(4))
                If IsNumeric(PARAM4) = True Then
                    Aran.Write(PARAM1, PARAM2, PARAM3, CInt(PARAM4))
                Else
                    Aran.Write(PARAM1, PARAM2, PARAM3, PARAM4)
                End If

            Case "REGDELKEY"  '//키삭제 하위키까지 모조리삭제
                PARAM1 = (임시버퍼(1))
                PARAM2 = (임시버퍼(2))
                Aran.DeleteKey(PARAM1, PARAM2)

            Case "REGDELVAL"  '//값 삭제
                PARAM1 = (임시버퍼(1))
                PARAM2 = (임시버퍼(2))
                PARAM3 = (임시버퍼(3))
                Aran.DeleteVal(PARAM1, PARAM2, PARAM3)
            Case Else
                'MsgBox("알수없는 스크립트:" & SCript)
                'Me.WLog("알수없는스크립트:" & SCript, "\script.txt")
        End Select
    End Sub


End Class




