Public Class ArinLog

    Dim file As System.IO.FileInfo
    Dim buffer As System.Text.StringBuilder
    Dim Datatable As DataTable
    Public Event RaiseMsg(time As String, gubun As String, msg As String)

    Public Enum ETYPE
        STARTUP
        SHUTDOWN
        [ERROR]
        NORMAL
        TCP
        KEYBOARD
        MOUSE
        PROCESS
        USERCONTROL
        BARCODE
        VISION
        PRINTER
        OCR
        OCRERROR
        MOTION
        SQL
        RS232
    End Enum

    Dim setdate As String = ""
    Public FlushTime As Date = Now  '//실기록완료한시간

    Public Function GetBuffer() As String
        Return buffer.ToString
    End Function

    Public Sub New()
        setdate = Now.ToString("yyMMdd")
        Me.file = New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\LOG\" & setdate & ".txt")
        If file.Directory.Exists = False Then file.Directory.Create()
        buffer = New System.Text.StringBuilder

        Datatable = New DataTable
        Datatable.Columns.Add("시간")
        Datatable.Columns.Add("형태")
        Datatable.Columns.Add("메세지")
    End Sub
    Public Sub Add(bodymsg As String, Optional autof As Boolean = False)
        Add(ETYPE.NORMAL, bodymsg, autof)
    End Sub
    Public Sub Add(TYPE As ETYPE, bodymsg As String, Optional autof As Boolean = False)
        Add(TYPE.ToString(), bodymsg, autof)
    End Sub

    Public Sub Add(TYPE As String, bodymsg As String, Optional autof As Boolean = False)
        If setdate <> Now.ToString("yyMMdd") Then   '//날짜가 달라지면 파일을 변경한다.
            Flush()
            setdate = Now.ToString("yyMMdd")
            Me.file = New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\LOG\" & setdate & ".txt")
        End If

        Dim nowdate As Date = Now
        Dim m As String = nowdate.ToString("yy-MM-dd HH:mm:ss") & "." & nowdate.Millisecond.ToString("000") & vbTab & TYPE.ToString.PadRight(20) & vbTab & bodymsg
        buffer.AppendLine(m)
        If autof OrElse buffer.Length > 100 OrElse TYPE = "ERROR Then    '//에러발생시에는 바로 플러싱" Then
            Flush()
        End If

        '//메세지발생함
        RaiseEvent RaiseMsg(nowdate.ToString("yy-MM-dd HH:mm:ss") & "." & nowdate.Millisecond.ToString("000"), TYPE, bodymsg)
    End Sub


    Public Function Flush() As Boolean
        Try
            My.Computer.FileSystem.WriteAllText(file.ToString, buffer.ToString, True)
            buffer = New System.Text.StringBuilder
            FlushTime = Now
            Return True
        Catch ex As Exception
            Return False
        End Try

    End Function

    Public Overrides Function toString() As String
        Try
            Return My.Computer.FileSystem.ReadAllText(file.FullName)
        Catch ex As Exception
            Return ""
        End Try
    End Function
End Class