
Public Class fFtpPath

    Public Selpath As String = ""
    Private ftpindex As Integer = 0

    Public Sub New(_host As String, _id As String, _pw As String, _port As Integer,
                   _passive As Boolean, _utf8 As Boolean, _
                   _BasePath As String)

        ' 이 호출은 디자이너에 필요합니다.
        InitializeComponent()

        tb_ftpid.Text = _id
        tb_ftppass.Text = _pw
        tb_ftpport.Text = _port.ToString()
        tb_ftpserver.Text = _host
        chk_ftpPassive.Checked = _passive
        chk_ftputf8.Checked = _utf8

        If String.IsNullOrEmpty(_BasePath) Then _BasePath = "/"
        _BasePath = _BasePath.Replace("\\", "\").Replace("//", "/")
        tb_ftppath.Text = _BasePath

        ' InitializeComponent() 호출 뒤에 초기화 코드를 추가하십시오.
    End Sub


    Private Sub fFtpPath_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Text = "(원본)FTP경로선택"
        Me.Show()
        My.Application.DoEvents()

        'RefreshFile(tb_ftppath.Text)
    End Sub

    Private Sub RefreshFile(dir As String)
        If String.IsNullOrEmpty(dir) Then
            dir = "/"
        End If

        btFtpSearch.Enabled = False
        btFtpSearch.Refresh()
        tb_ftppath.Text = dir
        lv_ftpde.Items.Clear()

        '//최상위가 아니라면 상위폴더이동을 추가해준다.
        If dir <> "/" Then
            Dim lvitem As ListViewItem = Me.lv_ftpde.Items.Add("..")
            lvitem.ForeColor = Color.DarkMagenta
        End If

        '//검출된데이터의 갯수
        Dim dataCount As UInteger = 0

        '//라이브러리종류별로 데이터를 조회한다.
        Dim isErr As Boolean = False
        Dim ErrMsg As String = ""
        FTP_0.CurrentDirectory = dir

        Dim ftpdir As FTPClients.FTPdirectory

        Try
            ftpdir = FTP_0.ListDirectoryDetail(dir)
            For Each info As FTPClients.FTPfileInfo In ftpdir.GetDirectories
                dataCount += 1
                Dim lvitem As ListViewItem = Me.lv_ftpde.Items.Add(info.Filename)
                lvitem.SubItems.Add(info.FileType.ToString())
                lvitem.SubItems.Add("-")
                lvitem.SubItems.Add(info.FileDateTime.ToString("yy-MM-dd HH:mm:ss"))
                lvitem.ForeColor = Color.Blue
            Next

            For Each info As FTPClients.FTPfileInfo In ftpdir.GetFiles("")
                dataCount += 1
                Dim lvitem As ListViewItem = Me.lv_ftpde.Items.Add(info.Filename)
                lvitem.SubItems.Add(info.FileType.ToString())
                lvitem.SubItems.Add(info.Size.ToString())
                lvitem.SubItems.Add(info.FileDateTime.ToString("yy-MM-dd HH:mm:ss"))
                lvitem.ForeColor = Color.Black
            Next
        Catch ex As Exception
            MsgBox("목록갱신실패" + vbCrLf + ex.Message, MsgBoxStyle.Critical, "확인")
        End Try

        btFtpSearch.Enabled = True
        btFtpSearch.Refresh()

        If (dataCount < 1) Then
            MsgBox(String.Format("경로 : {0}" + vbCrLf + "에서 검색된 파일이 없습니다", dir), MsgBoxStyle.Information, "확인")
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.Selpath = tb_ftppath.Text
        DialogResult = Windows.Forms.DialogResult.OK
    End Sub

    Private Sub lv_ftpde_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles lv_ftpde.MouseDoubleClick
        If lv_ftpde.SelectedItems.Count < 1 Then
            MsgBox("대상이 선택되지 않았습니다", MsgBoxStyle.Information, "확인")
            Return
        End If

        Dim lv As ListViewItem = lv_ftpde.SelectedItems(0)
        If lv.Text = ".." Then
            '//상위폴더로이동
            Dim curpath As String = tb_ftppath.Text
            If curpath.EndsWith("/") Then curpath = curpath.Substring(0, curpath.Length - 1)
            curpath = curpath.Replace("//", "/")
            Dim curs() As String = curpath.Split("/")
            Dim parentpath As String = ""
            For i As Integer = 1 To curs.Length - 1
                If curs(i - 1) = "" Then Continue For
                parentpath += "/" + curs(i - 1)
            Next
            tb_ftppath.Text = parentpath
            btFtpSearch.PerformClick()
        Else
            Dim ftype As String = lv.SubItems(1).Text
            Select Case ftype
                Case "Dir", "Directory"
                    Dim newdir As String = tb_ftppath.Text + "/" + lv.Text
                    newdir = newdir.Replace("//", "/")
                    tb_ftppath.Text = newdir
                    btFtpSearch.PerformClick()
                Case "File"
                    MsgBox("원본폴더를 선택하세요" + vbCrLf + _
                        "선택을 완료하였다면 상단의 '선택' 버튼을 클릭하세요", MsgBoxStyle.Information, "확인")
                    'If MsgBox("파일을 다운로드 하시겠습니까?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "확인") = MsgBoxResult.Yes Then
                    '    Dim file_local As String = path.GetTempPath + "\" + lv.Text
                    '    Dim file_remote As String = tb_ftppath.Text + "/" + lv.Text
                    '    file_local = file_local.Replace("\\", "\")
                    '    file_remote = file_remote.Replace("//", "/")
                    '    FTP.download(file_remote, file_local)

                    '    If System.IO.File.Exists(file_local) Then
                    '        Dim fi As New System.IO.FileInfo(file_local)
                    '        Dim fs As Long = Long.Parse(lv.SubItems(2).Text)
                    '        If fi.Length <> fs Then
                    '            MsgBox("다운로드된 파일의 용량이 일치하지 않습니다", MsgBoxStyle.Critical, "확인")
                    '            Return
                    '        Else
                    '            Dim cmd As String = "explorer " + path.GetTempPath
                    '            Shell(cmd, AppWinStyle.NormalFocus)
                    '        End If
                    '    Else
                    '        MsgBox("파일이 다운로드 되지 않았습니다", MsgBoxStyle.Critical, "확인")
                    '    End If

                    'End If
            End Select
        End If


    End Sub

    Private Sub btFtpSearch_Click(sender As Object, e As EventArgs) Handles btFtpSearch.Click

        If String.IsNullOrEmpty(tb_ftpserver.Text) Then
            MsgBox("FTP Server IP는 반드시 입력되어야 합니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        If Not IsNumeric(tb_ftpport.Text) Then
            MsgBox("FTP Port(기본값=21)가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            tb_ftpport.Text = "21"
            Return
        End If

        If String.IsNullOrEmpty(tb_ftppath.Text) Then
            tb_ftppath.Text = "/"
        End If

        FTP_0.host = tb_ftpserver.Text + ":" + tb_ftpport.Text
        FTP_0.user = tb_ftpid.Text
        FTP_0.pass = tb_ftppass.Text
        FTP_0.Passive = chk_ftpPassive.Checked
        FTP_0.utf8 = chk_ftputf8.Checked

        RefreshFile(tb_ftppath.Text)
    End Sub

End Class