Imports System.Data

Module Pub

    Structure Str_Macro
        Dim FileName As String
        Dim Desc As String
    End Structure

    '//일반변수
    Public PLog As ArinLog.ArinLog

    Public PathTempDown As String
    Public PathMacro As String
    Public PathJob As String
    Public PathList As String

    Public MacroPattern As String = "fileinfo"
    Public IniFile As String
    Public Prev_file As System.IO.FileInfo

    Public MaxRetryCount As Integer = 20 '//ftp 재시도 횟수 (10회 재시도 후 실패시에는 우선 넘어간다)
    Public RetrySleeptime As Integer = 2000

    '//FTP변수
    Public FTPServer As String = "127.0.0.1"
    Public FTPID As String = "anonymous"
    Public FTPPW As String = ""
    Public FTPPort As Integer = 21
    Public FTPPath As String = ""
    Public FTPPassive As Boolean = False
    Public FTPUTF8 As Boolean = False

    Public Enum EJobCmdType
        copy = 0
        move = 1
        delete = 2
    End Enum
    Public Structure SJobCommand
        Dim Mode As E_Runtype
        Dim SrcDir As String
        Dim SrcFile As String
        Dim DesDir As String
        Dim DesFile As String
        Dim isFTP As Boolean
    End Structure

    Public Function FileCheckSum(fn As String) As String
        Dim _md5 As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
        Using stream As System.IO.FileStream = File.OpenRead(fn)
            Dim checksum() As Byte = _md5.ComputeHash(stream)
            Return BitConverter.ToString(checksum).Replace("-", String.Empty)
        End Using
        Return "CHKERR"
    End Function

    Public Sub init()

        '//공용로그값
        PLog = New ArinLog.ArinLog()

        '//공용변수
        Prev_file = Nothing

        '//기본경로
        PathMacro = My.Application.Info.DirectoryPath & "\macro\" & MacroPattern
        PathJob = My.Application.Info.DirectoryPath & "\Job"
        PathList = My.Application.Info.DirectoryPath & "\List"

        '//작업용폴더확인
        If Not System.IO.Directory.Exists(PathJob) Then System.IO.Directory.CreateDirectory(PathJob)
        If Not System.IO.Directory.Exists(PathMacro) Then System.IO.Directory.CreateDirectory(PathMacro)
        If Not System.IO.Directory.Exists(PathList) Then System.IO.Directory.CreateDirectory(PathList)

        '//파일변수
        IniFile = My.Application.Info.DirectoryPath & "\macro\" & MacroPattern & "\default.ini"

    End Sub

    '''입력문자열이 파일로 변환되는지?
    Public Function isFileName(fn As String) As Boolean
        Try
            Dim fi As New System.IO.FileInfo(fn)
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Public Function DirCreate(path As String) As Boolean
        Try
            System.IO.Directory.CreateDirectory(path)
            Return True
        Catch ex As Exception
            PLog.Add(ArinLog.ArinLog.ETYPE.ERROR, "폴더생성실패(" + path + ") " + ex.Message, True)
            Return False
        End Try
    End Function

    'Public _ParseFormats As String() = { _
    '       "(?<dir>[\-dl])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{4})\s+(?<name>.+)", _
    '       "(?<dir>[\-dl])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{4})\s+(?<name>.+)", _
    '       "(?<dir>[\-dl])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?<name>.+)", _
    '       "(?<dir>[\-dl])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?<name>.+)", _
    '       "(?<dir>[\-dl])(?<permission>([\-r][\-w][\-xs]){3})(\s+)(?<size>(\d+))(\s+)(?<ctbit>(\w+\s\w+))(\s+)(?<size2>(\d+))\s+(?<timestamp>\w+\s+\d+\s+\d{2}:\d{2})\s+(?<name>.+)", _
    '       "(?<timestamp>\d{2}\-\d{2}\-\d{2}\s+\d{2}:\d{2}[Aa|Pp][mM])\s+(?<dir>\<\w+\>){0,1}(?<size>\d+){0,1}\s+(?<name>.+)"}

    'Public Function GetMatchingRegex(ByVal line As String) As System.Text.RegularExpressions.Match
    '    Dim rx As System.Text.RegularExpressions.Regex, m As System.Text.RegularExpressions.Match
    '    For i As Integer = 0 To _ParseFormats.Length - 1
    '        rx = New System.Text.RegularExpressions.Regex(_ParseFormats(i))
    '        m = rx.Match(line)
    '        If m.Success Then Return m
    '    Next
    '    Return Nothing
    'End Function

    'Public Enum SFtpType
    '    Link = 0
    '    File = 1
    '    Dir = 2
    'End Enum

    'Public Structure SFTPDetail
    '    Dim FileType As SFtpType
    '    Dim FileName As String
    '    Dim Size As Long
    '    Dim Permission As String
    '    Dim TimeStamp As String
    'End Structure

    'Public Function FtpDirParser(dirList() As String) As List(Of SFTPDetail)
    '    Dim retval As New List(Of SFTPDetail)
    '    For Each line As String In dirList
    '        Dim m As System.Text.RegularExpressions.Match = GetMatchingRegex(line)
    '        If Not m Is Nothing Then

    '            Dim newdr As New SFTPDetail

    '            Dim name As String = m.Groups("name").Value
    '            Dim perm As String = m.Groups("poermission").Value
    '            Dim _dir As String = m.Groups("dir").Value
    '            newdr.TimeStamp = m.Groups("timestamp").Value

    '            Dim filetype As String = ""
    '            Dim size As Long = 0
    '            If _dir.ToLower = "l" Then
    '                filetype = "LINK"
    '                size = 0
    '                newdr.FileType = SFtpType.Link
    '            ElseIf _dir.ToLower = "d" OrElse _dir.ToLower = "<dir>" Then
    '                filetype = "DIR"
    '                size = 0
    '                newdr.FileType = SFtpType.Dir
    '            Else
    '                filetype = "FILE"
    '                size = Long.Parse(m.Groups("size").Value)
    '                newdr.FileType = SFtpType.File
    '            End If

    '            newdr.Permission = perm
    '            newdr.FileName = name

    '            newdr.Size = size
    '            retval.Add(newdr)
    '        End If
    '    Next
    '    Return retval
    'End Function

    Public FTP_0 As FTPClients.Client_2

    Public Enum E_DesDirType
        desPath = 1 '//대상폴더
        CustomPath = 2 '//조합에의한 폴더
    End Enum
    Public Enum E_baktype
        none = 0
        Folder1 = 1
        CurrnetFolder = 2
        ParentFolder = 3
    End Enum
    Structure S_Log
        Dim Result As Char
        Dim OrgFile As String
        Dim DesFile As String
        Dim Orgpath As String
        Dim DesPath As String
        Dim Msg As String
    End Structure
    Enum E_Runtype
        Copy = 0
        Delete = 1
        Move = 2
    End Enum

    Public Log As ArrayList
    Public log2 As ArrayList
    Public Fileok As ArrayList  '//성공한 파일목록
    Public Ep As String
    Public BakTag As String = "-원본(" & Format(Now, "MMdd") & ")" '& "_MOV_D"

    Public Function GetBakDir1() As String
        Return MDiMain.tb_bakdir1.Text
    End Function

    Public Function SaveExcelFile(fn As String, dt As DataTable)
        Dim fp As New FarPoint.Win.Spread.FpSpread()
        fp.DataSource = dt
        Return fp.SaveExcel(fn, FarPoint.Excel.ExcelSaveFlags.SaveBothCustomRowAndColumnHeaders)
    End Function


    Public Function GetBackType1() As E_baktype
        Select Case MDiMain.cbBakType.SelectedIndex
            Case 0
                Return E_baktype.none
            Case 1
                Return E_baktype.Folder1
            Case 2
                Return E_baktype.CurrnetFolder
            Case 3
                Return E_baktype.ParentFolder
        End Select
        'If MDiMain.btBakNo.Pressed Then
        '    Return E_baktype.none
        'ElseIf MDiMain.btBakSrc.Pressed Then
        '    Return E_baktype.CurrnetFolder
        'ElseIf MDiMain.btBakUpDir.Pressed Then
        '    Return E_baktype.ParentFolder
        'Else
        '    Return E_baktype.Folder1
        'End If
    End Function

    Public Function GetrunType() As E_Runtype
        If MDiMain.btDel.Pressed Then
            Return 1
        ElseIf MDiMain.btMove.Pressed Then
            Return 2
        Else
            Return 0
        End If
    End Function
    Public Function GetWorkDIr() As String
        Try
            Return CStr(MDiMain.tb_workdir.Text).Replace("\\", "\").Replace("//", "/")
        Catch ex As Exception
            Return "작업폴더에 문제가있습니다"
        End Try
    End Function
    Public Function GetExtendFromMdi() As String
        Try
            Return "*." & MDiMain.tb_ext.Text
        Catch ex As Exception
            Return "*.*"
        End Try
    End Function
    Public Function GetExtendOnly() As String

        Return MDiMain.tb_ext.Text

    End Function
    Public Function GetSubDir() As Boolean
        Try
            Return MDiMain.chk_subdir.Checked
        Catch ex As Exception
            Return True
        End Try
    End Function

    Public Function GetSubdirType() As Short
        If MDiMain.chk_subdir.Checked Then
            Return 1
        Else
            Return 0
        End If
    End Function

    Public MyINI As New CommonClassv2.MyINI(My.Application.Info.DirectoryPath & "\main.ini")
    Public Arin As New CommonClassv2.ARINCLASS

    Public Sub Addlog(ByVal 성공여부 As String, ByVal 원본파일 As String, ByVal 대상파일 As String, ByVal 메세지 As String, Optional ByVal reset As Boolean = False)
        If reset Then Log = New ArrayList
        Log.Add(성공여부 & "/" & 원본파일 & "/" & 대상파일 & "/" & 메세지)
    End Sub

    Public Sub Addlog2(ByVal msg As String, Optional ByVal reset As Boolean = False)
        If reset Then log2 = New ArrayList
        log2.Add(">> " & msg)
        'Frm_log.RichTextBox1.AppendText(">> " & msg)
        'Frm_log.RichTextBox1.AppendText(vbCrLf)
    End Sub
    Public Sub makelog2(ByVal msg As String)
        Try
            Form_Status.RichTextBox1.AppendText(msg)
            Form_Status.RichTextBox1.AppendText(vbCrLf)
        Catch ex As Exception

        End Try

    End Sub

    Public Sub MakeBakLog1()
        Form_Status.RichTextBox2.Clear()
        For Each Msg As String In Backupfolder1
            Form_Status.RichTextBox2.AppendText(Msg)
            Form_Status.RichTextBox2.AppendText(vbCrLf)
        Next
    End Sub



    Public Function getSP() As Integer
        If String.IsNullOrEmpty(MDiMain.tb_sttrange.Text) Then MDiMain.tb_sttrange.Text = "1"
        Return MDiMain.tb_sttrange.Text  '//목록에서 시작줄번호
    End Function

    Public Sub Errlog(ByVal amsg As String)
        Dim Fs As New System.IO.FileStream(My.Application.Info.DirectoryPath & "\error.txt", FileMode.Create)
        Dim Sw As New System.IO.StreamWriter(Fs, System.Text.Encoding.Default)
        Sw.WriteLine("시간:" & Now.ToShortDateString & ":" & Now.ToShortTimeString & vbCrLf & amsg)
        Sw.Close()
        Sw.Dispose()
        Fs.Close()
        Fs.Dispose()
    End Sub


End Module
