Public Class FileManager

    Private Sub FileManager_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Me.SAVE_Setting()
    End Sub
    Private Sub FileManager_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.LOAD_Setting()

    End Sub
    Private Sub 목록지우기ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cm_clear.Click
        Me.MyFpoint1.ActiveSheet.RowCount = 0
    End Sub

    Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb_ren_left.TextChanged, tb_ren_right.TextChanged
        Me.lb_newfilename.Text = "* 새로운 파일명 : " & Me.tb_ren_left.Text & "testfilename1" & Me.tb_ren_right.Text
    End Sub


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If Me.tb_ren_left.Text = "" AndAlso Me.tb_ren_right.Text = "" Then
            NOTICE("아무것도 입력되어있지 않습니다", Color.Tomato, Me.lb_msg)
            Me.tb_ren_left.Focus()
            Return
        End If
        Dim TG As New System.IO.DirectoryInfo(DirListBox1.Path)
        If Not TG.Exists Then
            MsgBox("그림폴더가 존재하지 않습니다" & vbCrLf & vbCrLf & "그림폳더를 지정해주세요", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim Msg As New System.Text.StringBuilder("폴더 : " & DirListBox1.Path)
        Msg.AppendLine()
        If Me.CHK_SUBDIR.Checked Then
            Msg.AppendLine("아래의 모든파일과 하위폴더의")
        Else
            Msg.AppendLine("아래의 모든파일의")
        End If

        Msg.AppendLine("그림파일에대한 붙이기 작업을 실행하시겠습니까?")
        If MsgBox(Msg.ToString, MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then
            NOTICE("취소되었습니다", Color.Tomato, Me.lb_msg)
            Return
        End If

        Me.MyFpoint1.ActiveSheet.RowCount = 0

        '//현재폴더로부터 하위폴더(옵션)
        Dim NEwName As String = ""
        For Each TF As System.IO.FileInfo In TG.GetFiles("*." & Me.cmb_picEXT.Text, IIf(Me.CHK_SUBDIR.Checked, 1, 0))
            NEwName = Me.tb_ren_left.Text & TF.Name.Substring(0, TF.Name.LastIndexOf(".")) & Me.tb_ren_right.Text & "." & Me.cmb_picEXT.Text
            TF.MoveTo(TF.DirectoryName & "\" & NEwName)
            ADdLog(TF.Name, NEwName, TF.DirectoryName)
        Next
    End Sub

    Private Sub ADdLog(ByVal src As String, ByVal target As String, ByVal memo As String)
        With Me.MyFpoint1.ActiveSheet
            .RowCount += 1    '//행증가
            .Cells(.RowCount - 1, 0).Text = src
            .Cells(.RowCount - 1, 1).Text = target
            .Cells(.RowCount - 1, 2).Text = memo
        End With
    End Sub


    Private Sub bt_picselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_picselect.Click
        Dim A As New FolderBrowserDialog
        A.RootFolder = Environment.SpecialFolder.MyComputer
        A.SelectedPath = DirListBox1.Path
        If A.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
            MsgBox("선택이 취소되었습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If
        DirListBox1.Path = A.SelectedPath
    End Sub

    Private Sub ContextMenuStrip1_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        If Me.MyFpoint1.ActiveSheet.RowCount = 0 Then
            Me.cm_out.Enabled = False
        Else
            Me.cm_out.Enabled = True
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click    '//이름치환
        If Me.tb_chg1.Text = "" AndAlso Me.tb_chg2.Text = "" Then
            NOTICE("아무것도 입력되어있지 않습니다", Color.Tomato, Me.lb_msg)
            Me.tb_chg1.Focus()
            Return
        End If

        Dim TG As New System.IO.DirectoryInfo(DirListBox1.Path)
        If Not TG.Exists Then
            MsgBox("그림폴더가 존재하지 않습니다" & vbCrLf & vbCrLf & "그림폳더를 지정해주세요", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim Msg As New System.Text.StringBuilder("폴더 : " & DirListBox1.Path)
        Msg.AppendLine()
        If Me.CHK_SUBDIR.Checked Then
            Msg.AppendLine("아래의 모든파일과 하위폴더의")
        Else
            Msg.AppendLine("아래의 모든파일의")
        End If

        Msg.AppendLine("그림파일에대한 치환 작업을 실행하시겠습니까?")
        If MsgBox(Msg.ToString, MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then
            NOTICE("취소되었습니다", Color.Tomato, Me.lb_msg)
            Return
        End If

        Me.MyFpoint1.ActiveSheet.RowCount = 0

        '//현재폴더로부터 하위폴더(옵션) - 파일명 자르기를 수행한다.
        Dim NEwName As String = ""

        For Each TF As System.IO.FileInfo In TG.GetFiles("*." & Me.cmb_picEXT.Text, IIf(Me.CHK_SUBDIR.Checked, 1, 0))
            NEwName = TF.Name.Substring(0, TF.Name.LastIndexOf("."))
            For Each SI As String In Me.tb_chg1.Text.Split("/")
                NEwName = NEwName.Replace(SI, Me.tb_chg2.Text)
            Next
            ADdLog(TF.Name, NEwName & "." & Me.cmb_picEXT.Text, TF.DirectoryName)
            TF.MoveTo(TF.DirectoryName & "\" & NEwName & "." & Me.cmb_picEXT.Text)
        Next
        MsgBox(Me.MyFpoint1_Sheet1.RowCount & "개의 파일작업을 수행했습니다", MsgBoxStyle.Information, "확인")
    End Sub

#Region "설정저장/불러오기 : Load 와 Closing 에서 발생"
    Private Sub LOAD_Setting()
        Dim A As New MyINI2(MyPath.Current & "\setting.ini")
        Try
            'dirlistbox1.path = A.Read("picmanager", "DefaultPicDir", "c:\windows").Trim(Chr(0))
            Me.DirListBox1.Path = A.Read("picmanager", "DefaultPicDir", "c:\windows").Trim(Chr(0))
            'Me.cmb_PICTYPE.SelectedIndex = A.Read("pic", "pictype", 3)
            Me.cmb_picEXT.SelectedIndex = A.Read("picmanager", "picext", 1)
            Me.CHK_SUBDIR.Checked = A.Read("picmanager", "subdir", True)
        Catch ex As Exception
            DirListBox1.Path = vbNullString
            Me.cmb_picEXT.SelectedIndex = 3
            'Me.cmb_PICTYPE.SelectedIndex = 1
            Me.CHK_SUBDIR.Checked = True
        End Try
        A = Nothing
    End Sub
    Private Sub SAVE_Setting()
        Dim A As New MyINI2(MyPath.Current & "\setting.ini")

        Try
            A.Write("picmanager", "DefaultPicDir", Me.DirListBox1.Path)
            'A.Write("pic", "pictype", Me.cmb_PICTYPE.SelectedIndex)
            A.Write("picmanager", "picext", Me.cmb_picEXT.SelectedIndex)
            A.Write("picmanager", "subdir", Me.CHK_SUBDIR.Checked)
        Catch ex As Exception

        End Try
        A = Nothing
    End Sub
#End Region


    Private Sub bt_exit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_exit.Click   '//닫기
        Me.Close()
    End Sub

    Private Sub DriveListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DriveListBox1.SelectedIndexChanged
        Me.DirListBox1.Path = Me.DriveListBox1.Items(Me.DriveListBox1.SelectedIndex).ToString
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click    '//파일삭제
        '//tb_del1.text  에 들어있는 아이템을 가지고 파일을 삭제한다.
        If Me.tb_del1.Text = "" AndAlso Me.tb_del1.Text = "" Then
            NOTICE("아무것도 입력되어있지 않습니다", Color.Tomato, Me.lb_msg)
            Me.tb_del1.Focus()
            Return
        End If

        Dim TG As New System.IO.DirectoryInfo(DirListBox1.Path)
        If Not TG.Exists Then
            MsgBox("그림폴더가 존재하지 않습니다" & vbCrLf & vbCrLf & "그림폳더를 지정해주세요", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim Msg As New System.Text.StringBuilder("폴더 : " & DirListBox1.Path)
        Msg.AppendLine()
        If Me.CHK_SUBDIR.Checked Then
            Msg.AppendLine("아래의 모든파일과 하위폴더의")
        Else
            Msg.AppendLine("아래의 모든파일의")
        End If

        Msg.AppendLine("그림파일에대한 삭제 작업을 실행하시겠습니까?")
        If MsgBox(Msg.ToString, MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then
            NOTICE("취소되었습니다", Color.Tomato, Me.lb_msg)
            Return
        End If

        Me.MyFpoint1.ActiveSheet.RowCount = 0

        '//현재폴더로부터 하위폴더(옵션) - 파일명 자르기를 수행한다.
        Dim NEwName As String = ""

        For Each TF As System.IO.FileInfo In TG.GetFiles("*." & Me.cmb_picEXT.Text, IIf(Me.CHK_SUBDIR.Checked, 1, 0))
            NEwName = TF.Name.Substring(0, TF.Name.LastIndexOf("."))
            For Each SI As String In Me.tb_del1.Text.Split("/")
                'MsgBox(NEwName.IndexOf(SI))
                If NEwName.IndexOf(SI) >= 0 Then '//존재하는경우다 이럴경우는 삭제를 해버린다.
                    ADdLog(TF.Name, "", "[삭제대상]")
                    TF.MoveTo(TF.DirectoryName & "\[삭제대상]" & TF.Name)
                    Exit For
                End If
            Next
        Next

        MsgBox(Me.MyFpoint1_Sheet1.RowCount & "개의 파일작업을 수행했습니다" & vbCrLf & vbCrLf & "잠시후 대상폴더가 열립니다", MsgBoxStyle.Information, "확인")
        Process.Start("explorer.exe", Me.DirListBox1.Path)
    End Sub


    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Dim OD As New OpenFileDialog
        'Dim Aranini As New MyINI2(IniFile)
        'OD.FileName = Me.lb_file.Text
        OD.Filter = "MS Office Excel WorkSheet(*.xls)|*.xls"
        OD.FilterIndex = 1
        ' OD.RestoreDirectory = True
        If OD.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
            NOTICE("불러오기가 취소되었습니다", Me.lb_msg)
        Else
            'Aranini.Write("normal", "file", OD.FileName)
            'Me.lb_file.Text = OD.FileName
            ReadXls(OD.FileName)
        End If
    End Sub

    Private Sub ReadXls(ByVal Filename As String)   '//Read xls File
        Me.MyFpoint2.OpenExcel(Filename)
        For Each Cl As FarPoint.Win.Spread.Column In Me.MyFpoint2.ActiveSheet.Columns '//Set columns label
            Cl.Label = Cl.Index + 1
        Next
        '//연속 5개의 공백이 보이면 카운트를 종료한다.
        Dim 공백 As Int16 = 0
        For Each Row As FarPoint.Win.Spread.Row In Me.MyFpoint2.ActiveSheet.Rows
            If Me.MyFpoint2.ActiveSheet.Cells(Row.Index, 0).Text = "" Then 공백 += 1
            If 공백 >= 5 Then
                Me.MyFpoint2.ActiveSheet.RowCount = Row.Index + 1 - 3
                Exit For
            End If
        Next
    End Sub

    Private Sub tb_ref1__TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb_ref1.TextChanged, tb_ref2.TextChanged, tb_ref3.TextChanged, tb_ref4.TextChanged, tb_ref5.TextChanged, tb_ref6.TextChanged
        Dim A As TextBox = CType(sender, TextBox)
        If A.Text.Length <= 0 Then Exit Sub
        Select Case A.Text.Substring(0, 1)
            Case "#"  ''//값을 직접 입력했을때다.
                A.BackColor = Color.SteelBlue
            Case Else
                If IsNumeric(A.Text) Then
                    A.BackColor = Color.White
                Else
                    A.BackColor = Color.Tomato
                End If
        End Select

    End Sub

    Private Function CheckCtrl(ByVal Obj As TextBox) As Boolean
        If Obj.Text <> "" AndAlso Obj.Text.Substring(0, 1) <> "#" AndAlso Not IsNumeric(Obj.Text) Then    '//참조1의 시작값이 #라면(직접입력)
            MsgBox("입력값에 문제가 있습니다." & vbCrLf & "값의 직접입력은  먼저 # 를 입력후에 입력하세요" & vbCrLf & "예) _01을 입력할시 #_01" & vbCrLf & "그외는 숫자(열번호)만 가능합니다", MsgBoxStyle.Critical, "확인")
            Obj.Focus()
            Return False
        End If
        Return True
    End Function
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        '//tB_ref1~6 에의한 파일명 조합이다. 조합후 동일한 파일을 삭제한다.
        If Me.tb_ref1.Text = "" AndAlso Me.tb_ref2.Text = "" AndAlso Me.tb_ref3.Text = "" AndAlso Me.tb_ref4.Text = "" AndAlso Me.tb_ref5.Text = "" AndAlso Me.tb_ref6.Text = "" Then
            NOTICE("아무것도 입력되어있지 않습니다", Color.Tomato, Me.lb_msg)
            Me.tb_ref1.Focus()
            Return
        End If

        Dim TG As New System.IO.DirectoryInfo(DirListBox1.Path)
        If Not TG.Exists Then
            MsgBox("그림폴더가 존재하지 않습니다" & vbCrLf & vbCrLf & "그림폳더를 지정해주세요", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim Msg As New System.Text.StringBuilder("폴더 : " & DirListBox1.Path)
        Msg.AppendLine()
        If Me.CHK_SUBDIR.Checked Then
            Msg.AppendLine("아래의 모든파일과 하위폴더의")
        Else
            Msg.AppendLine("아래의 모든파일의")
        End If

        Msg.AppendLine("그림파일에대한 삭제 작업을 실행하시겠습니까?")
        If MsgBox(Msg.ToString, MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then
            NOTICE("취소되었습니다", Color.Tomato, Me.lb_msg)
            Return
        End If

        If Not CheckCtrl(Me.tb_ref1) Then Return '//컨트롤들의 셋티잉 올바른가?
        If Not CheckCtrl(Me.tb_ref2) Then Return
        If Not CheckCtrl(Me.tb_ref3) Then Return
        If Not CheckCtrl(Me.tb_ref4) Then Return
        If Not CheckCtrl(Me.tb_ref5) Then Return
        If Not CheckCtrl(Me.tb_ref6) Then Return


        '----------------------Main start ----------------------
        Me.MyFpoint1.ActiveSheet.RowCount = 0   '//로그내역을삭제한다.
        Dim NEwName As String = ""        '//현재폴더로부터 하위폴더(옵션) - 파일명 자르기를 수행한다.

        '//목록으로부터이니 모든 목록을 돈다.
        Dim R1, R2, R3, R4, R5, R6 As String
        Dim Fname As String

        Me.pbar1.Minimum = 0
        Me.pbar1.Value = 0
        Me.pbar1.Maximum = Me.MyFpoint2.ActiveSheet.RowCount

        'ADdLog("1", "", "[start]" & TG.FullName)

        Dim SttRng, EndRng As Integer
        SttRng = Me.tb_sttrng.Text
        EndRng = IIf(Me.tn_endrng.Text = 0, Me.MyFpoint2.ActiveSheet.RowCount, Me.tn_endrng.Text)

        For Each Row As FarPoint.Win.Spread.Row In Me.MyFpoint2.ActiveSheet.Rows
            If Row.Index >= SttRng AndAlso Row.Index <= EndRng Then '//검색범위에 해당하는것만
                'MsgBox("!!")
                Me.pbar1.Value = Row.Index
                'ADdLog(Row.Index, "", "[확인중]" & TG.FullName)
                R1 = Me.GetFPData(Me.tb_ref1, Row)
                R2 = Me.GetFPData(Me.tb_ref2, Row)
                R3 = Me.GetFPData(Me.tb_ref3, Row)
                R4 = Me.GetFPData(Me.tb_ref4, Row)
                R5 = Me.GetFPData(Me.tb_ref5, Row)
                R6 = Me.GetFPData(Me.tb_ref6, Row)
                Fname = R1 & R2 & R3 & R4 & R5 & R6 & "." & Me.cmb_picEXT.Text   '//파일명 완성 ; 이제 찾아서 해당파일명만 바꺼주면된다.
                If Fname.Trim <> "" Then
                    'ADdLog(Fname, "", "[확인중]" & TG.FullName)
                    For Each TF As System.IO.FileInfo In TG.GetFiles(Fname, IIf(Me.CHK_SUBDIR.Checked, 1, 0))
                        ADdLog(Fname, TF.Name, "[삭제대상]")
                        TF.MoveTo(TF.DirectoryName & "\[삭제대상]" & TF.Name)
                    Next
                Else
                    ADdLog(Fname, "", "[조합된 값이 없음]")
                End If
            End If
        Next
        MsgBox(Me.MyFpoint1_Sheet1.RowCount & "개의 파일작업을 수행했습니다" & vbCrLf & vbCrLf & "잠시후 대상폴더가 열립니다", MsgBoxStyle.Information, "확인")
        Process.Start("explorer.exe", Me.DirListBox1.Path)
    End Sub



    Private Function GetFPData(ByVal sender As TextBox, ByVal Drow As FarPoint.Win.Spread.Row) As String
        '//만약 날짜포맷이면 FORMAT 을 지정해서 사용한다"

        Dim SUbidx As Integer

        If sender.Text = "" Then '//즉 없다는뜻이다.
            Return ""
        ElseIf sender.Text.Substring(0, 1) = "#" Then
            Return sender.Text.Substring(1)
        Else '//있다.
            SUbidx = sender.Text
            Return Me.MyFpoint2.ActiveSheet.Cells(Drow.Index, CInt(SUbidx - 1)).Text
        End If
    End Function
End Class