''dsmplayer.wxb''

Dim sortOrder As Integer = FALSE

Dim mFilter As String = "All files (*.*)|*.*|All Music files|*.aac;*.cda;*.flac;*.mp3;*.m4a;*.ogg;*.opus;*.wav|" &
  "aac files (*.aac)|*.aac|cda files (*.cda)|*.cda|flac files (*.flac)|*.flac|mp3 files (*.mp3)|*.mp3|m4a files (*.m4a)|*.m4a|ogg files (*.ogg)|*.ogg|opus files (*.opus)|*.opus|wav files (*.wav)|*.wav"

'create the playlist dialog
Sub onCreatePlaylist(event As wxCommandEvent)
  Dim cfg As wxFileConfig = wxFileConfig("", "", playerIni)
  cfg.SetPath("/Playlist")

  Dim explorerMedia As wxGenericDirCtrl = DynamicCast("wxGenericDirCtrl", musicFrame.FindWindowByName("explorermedia"))
  Dim sd = wxDialog(musicFrame, -1, _("Create Playlist"), wxDefaultPosition, wxSize(990, 630))
  Dim sizeX = sd.GetClientSizeWidth()
  Dim sizeY = sd.GetClientSizeHeight()
  Dim x, y As Integer
  x, y = wxDisplaySize()
  sd.SetPosition(wxPoint((x - sizeX)/ 2, (y - sizeY)/ 2))

  Dim plPanel As wxPanel = wxPanel(sd, -1)
  Dim filePath As String = explorerMedia.GetPath()

  Dim gb As wxGridBagSizer = wxGridBagSizer(3, 3)

  'left side
  Dim filectrl As wxGenericFileCtrl = wxGenericFileCtrl(plPanel, -1, "", "", mFilter, wxFC_OPEN|wxFC_MULTIPLE, wxDefaultPosition, wxDefaultSize, "batchFileCtrl")
  filectrl.SetSizeXY((sizeX - 190)/ 2, 400)
  fileCtrl.SetFilterIndex(1)
  fileCtrl.SetDirectory(filePath)
  gb.AddSpacer(6, 2, wxGBPosition(1, 0))
  gb.AddWindow(fileCtrl, wxGBPosition(1, 1), wxGBSpan(13, 1), wxEXPAND)

  'controls in the middle
  Dim btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_FOLDER_OPEN, wxART_OTHER, wxSize(16 * ps, 16 * ps)), wxDefaultPosition, wxSize(50, 30))
  btn.SetToolTip(_("Open a directory"))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onChangeFilePath")
  gb.AddWindow(btn, wxGBPosition(1, 2), wxDefaultSpan, 0)

  btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_FILE_OPEN, wxART_OTHER, wxSize(16 * ps, 16 * ps)), wxDefaultPosition, wxSize(50, 30))
  btn.SetToolTip(_("Open a playlist"))
  btn.SetName("openButton")
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onOpenPlaylist")
  gb.AddWindow(btn, wxGBPosition(1, 3), wxDefaultSpan, wxRIGHT|0)
  gb.AddSpacer(1, 3, wxGBPosition(2, 2), wxGBSpan(1, 2), 0)

  Dim cb As wxCheckBox = wxCheckBox(plPanel, -1, _("Report Mode"))
  Connect(cb, -1, wxEVT_COMMAND_CHECKBOX_CLICKED, "onReportMode")
  cb.SetValue(cfg.Read("ReportMode", FALSE))
  gb.AddWindow(cb, wxGBPosition(3, 2), wxGBSpan(1, 2), 0)

  Dim cb1 As wxCheckBox = wxCheckBox(plPanel, -1, _("Add Subdirs"))'
  cb1.SetName("includeCb")
  cb1.SetValue(cfg.Read("IncludeSubs", FALSE))
  gb.AddWindow(cb1, wxGBPosition(4, 2), wxGBSpan(1, 2), 0)
  gb.AddSpacer(1, 3, wxGBPosition(5, 2))

  btn = wxButton(plPanel, -1, _("Add"), wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onAddSelectedFiles")
  gb.AddWindow(btn, wxGBPosition(6, 2), wxGBSpan(1, 2), wxEXPAND)

  btn = wxButton(plPanel, -1, _("Add all"), wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onAddAllFiles")
  gb.AddWindow(btn, wxGBPosition(7, 2), wxGBSpan(1, 2), 0)

  btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_GO_UP) , wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onMoveFilesUp")
  gb.AddWindow(btn, wxGBPosition(8, 2), wxGBSpan(1, 2), 0)

  btn = wxBitmapButton(plPanel, -1, wxArtProvider_GetBitmap(wxART_GO_DOWN), wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onMoveFilesDown")
  gb.AddWindow(btn, wxGBPosition(9, 2), wxGBSpan(1, 2), 0)

  btn = wxButton(plPanel, -1, _("Remove"), wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onRemoveSelectedFiles")
  gb.AddWindow(btn, wxGBPosition(10, 2), wxGBSpan(1, 2), 0)

  btn = wxButton(plPanel, -1, _("Remove all"), wxDefaultPosition, wxSize(140, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onRemoveAllFiles")
  gb.AddWindow(btn, wxGBPosition(11, 2), wxGBSpan(1, 2), 0)
  gb.AddSpacer(1, 1, wxGBPosition(12, 2), wxGBSpan(1, 2), 0)

  'right side
  'create the file list window
  Dim fileList As wxListBox = wxListBox(plPanel, -1, wxDefaultPosition, wxSize((sizeX - 190)/ 2, 400), 0, [], wxLB_MULTIPLE | wxLB_EXTENDED|wxLB_HSCROLL)
  fileList.SetName("batchFileList")
  gb.AddWindow(filelist, wxGBPosition(1, 4), wxGBSpan(13, 1), wxEXPAND)
  gb.AddSpacer(10, 10, wxGBPosition(1, 4), wxGBSpan(13, 1))

  btn = wxButton(plPanel, -1, _("Sort List"), wxDefaultPosition, wxSize(120, 25))
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onSortPlaylistFiles")
  gb.AddWindow(btn, wxGBPosition(14, 4), wxDefaultSpan, 0)

  'create a checkbox to remove the numbers at the beginning of the file name when saving
  Dim cb2 As wxCheckBox = wxCheckBox(plPanel, -1, _("Remove title numbers in the filename when saving"))
  cb2.SetName("removeCb")
  cb2.SetValue(cfg.Read("RemoveNum", FALSE))
  gb.AddWindow(cb2, wxGBPosition(16, 4), wxDefaultSpan, 0)

  'create save button
  Dim saveButton = wxButton(plPanel, wxID_SAVE, _("Save playlist"))
  Connect(saveButton, wxID_SAVE, wxEVT_COMMAND_BUTTON_CLICKED, "onSaveButtonClick")
  gb.AddWindow(saveButton, wxGBPosition(17, 4), wxGBSpan(1, 1), wxEXPAND)

  'path options
  Dim text = wxStaticText(plPanel, -1, _("Destination file:"))
  gb.AddWindow(text, wxGBPosition(15, 1), wxDefaultSpan, 0)
  
  Dim listPath As wxFilePickerCtrl = wxFilePickerCtrl(plPanel, -1, fileCtrl.GetShownDirectory() &DELIMITER_CHAR&"playlist.m3u", "...", "*.m3u", wxDefaultPosition, wxDefaultSize, wxFLP_SAVE|wxFLP_USE_TEXTCTRL)
  listPath.SetName("newFileName")
  gb.AddWindow(listPath, wxGBPosition(16, 1), wxDefaultSpan, wxEXPAND)

  btn = wxButton(plPanel, -1, _("current browser directory"), wxDefaultPosition, wxSize(-1, 25))
  btn.SetName("curDirButton")
  Connect(btn, -1, wxEVT_COMMAND_BUTTON_CLICKED, "onSetCurrentDir")
  gb.AddWindow(btn, wxGBPosition(17, 1), wxDefaultSpan, wxEXPAND)

  gb.AddSpacer(1, 10, wxGBPosition(18, 0), wxGBSpan(1, 5))

  Dim cancelButton As wxButton = wxButton(plPanel, wxID_CANCEL, _("Close playlist dialog"))
  gb.AddWindow(cancelButton, wxGBPosition(19, 1), wxGBSpan(1, 5), wxEXPAND)

  plPanel.SetAutoLayout(TRUE)
  plPanel.SetSizerAndFit(gb)

  sd.ShowModal()

  cfg.Write("ReportMode", cb.GetValue())
  cfg.Write("IncludeSubs", cb1.GetValue())
  cfg.Write("RemoveNum", cb2.GetValue())
  sd.Destroy()
End Sub


Sub onAddSelectedFiles(event As wxCommandEvent)
  Dim ctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))

  Dim allFiles As wxArrayString = ctrl.GetPaths()
  For i = 0 To allFiles.Count() - 1
    If !wxFileName_DirExists(allFiles.Item(i)) Then fCtrl.Append(allFiles.Item(i))
  Next

  allFiles.Clear()
  ~allFiles
End Sub


Sub onAddAllFiles(event As wxCommandEvent)
  Dim ctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  Dim ictrl = DynamicCast("wxCheckBox", wxFindWindowByName("includeCb"))
  Dim allFiles As wxArrayString = wxArrayString()
  Dim Style As Integer = IIf(iCtrl.GetValue(), wxDIR_FILES|wxDIR_DIRS, wxDIR_FILES)

  Dim wild As wxStringTokenizer = wxStringTokenizer(ctrl.GetWildcard(), "|")
  Dim fIndex As Integer = ctrl.GetFilterIndex()
  Dim cnt As Integer = 0
  Dim filter As String

  For i = 1 To wild.CountTokens()/ 2
    wild.GetNextToken()
    filter = wild.GetNextToken()
    If cnt = fIndex Then Break
    cnt += 1
  Next

  ctrl.SetFocus()
  wild.SetString(filter, ";")

  While TRUE
    wxDir_GetAllFiles(ctrl.GetShownDirectory(), allFiles, wild.GetNextToken(), Style)
    If !wild.CountTokens() Then Break
  Wend

  allFiles.Sort()
  fCtrl.AppendArrayString(allFiles)
  allFiles.Clear()
  ~allFiles
  ~wild
End Sub


Sub onRemoveSelectedFiles(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  For i = fCtrl.GetCount() - 1 To 0 Step -1
    If fctrl.IsSelected(i) Then fCtrl.Delete(i)
  Next
End Sub


Sub onRemoveAllfiles(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  fCtrl.Clear()
End Sub


Sub onChangeFilePath(event As wxCommandEvent)
  Dim win = wxFindWindowByName("batchFileCtrl")
  Dim ctrl = DynamicCast("wxGenericFileCtrl", win)

  Dim dlg As wxDirDialog = wxDirDialog(Nothing, _("Choose a path:"), ctrl.GetShownDirectory())
  If dlg.ShowModal()= wxID_OK Then ctrl.SetDirectory(dlg.GetPath() &DELIMITER_CHAR)
  dlg.Destroy()
End Sub


Sub onSortPlaylistFiles(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))

  'sorting with wxArrayString is case sensitive
  'so use two arraystrings to sort 
  Dim allFiles As wxArrayString = wxArrayString()
  Dim allFilesC As wxArrayString = wxArrayString()
  Dim Item As String

  'add all items to the arraystrings
  For i = 0 To fctrl.GetCount() - 1
    Item = fCtrl.GetString(i)
    'add items in the right case for insert
    allFiles.Add(Item)
    'add items in lower case to sort
    allFilesC.Add(LCase(Item))
  Next

  'sort the lower case items
  allFilesC.Sort(sortOrder)

  fCtrl.Clear()
  'append the sorted items
  For i = 0 To allfiles.Count() - 1
    fCtrl.Append(allfiles.Item(allfiles.INDEX(allfilesC.Item(i), FALSE)))
  Next

  allFiles.Clear()
  allFilesC.Clear()
  ~allFiles
  ~allFilesC

  sortOrder = !sortOrder
End Sub


'moves the selected items up one level
Sub onMoveFilesUp(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  Dim Item

  For i = 1 To fctrl.GetCount() - 1
    If fctrl.IsSelected(i) Then
      'swap with the top item(move up)
      If !fctrl.IsSelected(i - 1) Then
        Item = fctrl.GetString(i)
        fctrl.Delete(i)
        fctrl.Insert(Item, i - 1)
        fctrl.SetSelection(i - 1, TRUE)
      End If
    End If
  Next
End Sub


Sub onMoveFilesDown(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  Dim Item

  For i = fctrl.GetCount() - 2 To 0 Step -1
    If fctrl.IsSelected(i) Then
      'swap with the top item(move up)
      If !fctrl.IsSelected(i + 1) Then
        Item = fctrl.GetString(i)
        fctrl.Delete(i)
        fctrl.Insert(Item, i + 1)
        fctrl.SetSelection(i + 1, TRUE)
      End If
    End If
  Next
End Sub


Sub onReportMode(event As wxCommandEvent)
  setReportMode(event.IsChecked())
End Sub


Sub setReportMode(mode As Integer)
  Dim ctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  If mode Then
    ctrl.ChangeToReportMode()
  Else
    ctrl.ChangeToListMode()
  End If
End Sub


Sub onSetCurrentDir(event As wxCommandEvent)
  Dim fctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  Dim ctrl = DynamicCast("wxFilePickerCtrl", wxFindWindowByName("newFileName"))
  Dim FileName As wxFileName = wxFileName(ctrl.GetValue())

  ctrl.SetValue(fctrl.GetDirectory() &DELIMITER_CHAR &IIf(ctrl.GetValue()= "", "playlist.m3u", FileName.GetName()))
  ~FileName
End Sub


Sub onOpenPlaylist(event As wxCommandEvent)
  Dim explorerMedia As wxGenericDirCtrl = DynamicCast("wxGenericDirCtrl", musicFrame.FindWindowByName("explorermedia"))
  Dim ctrl = DynamicCast("wxFilePickerCtrl", wxFindWindowByName("newFileName"))
  Dim win As wxWindow = ctrl.GetParent()
  Dim path As String = IIf(ctrl.GetPath()= "", explorerMedia.GetFilePath(), ctrl.GetPath())
  Dim dlg As wxFileDialog = wxFileDialog(win, _("Choose a playlist:"), wxPathOnly(path), "", "*.m3u")

  If dlg.ShowModal() = wxID_OK Then
    loadPlayListMedia(dlg.GetPath(), FALSE, TRUE)
    ctrl.SetPath(dlg.GetPath())
  End If

  dlg.Destroy()
End Sub


Sub onSaveButtonClick(event As wxCommandEvent)
  Dim ctrl = DynamicCast("wxFilePickerCtrl", wxFindWindowByName("newFileName"))
  Dim path As String = ctrl.GetPath()

  If path = "" Then
    Dim dl = wxGenericMessageDialog(Nothing, _("No file specified!"), _("Hint"), wxCENTRE|wxICON_INFORMATION|wxDIALOG_NO_PARENT)
    dl.ShowModal()
    Return

  Elseif wxFileExists(path) Then
    dl = wxGenericMessageDialog(Nothing, _("The file already exists.") &"\n" &
    _("Should it be overwritten?"), _("Save Playlist?"), wxYES_NO|wxYES_DEFAULT|wxCENTRE|wxICON_WARNING|wxDIALOG_NO_PARENT)

    'wxNo = 5104 in wxGenericMessageDialog
    If dl.ShowModal() = 5104 Then Return
  End If
  
  Dim fctrl = DynamicCast("wxListBox", wxFindWindowByName("batchFileList"))
  Dim removeCB As wxCheckBox = DynamicCast("wxCheckBox", wxFindWindowByName("removeCb"))
  Dim title As String
  Dim filePath As String
  Dim buffer As String
  Dim Remove As Integer = removeCB.IsChecked()
  Dim s As wxString = wxString()

  Try
    Dim freenum = FreeFile()
    Open path For Output As #freenum
    Print #freenum, "#EXTM3U"

    For i = 0 To fctrl.GetCount() - 1
      filePath = fctrl.GetString(i)
      title = wxFileNameFromPath(filePath)
      s.SetValue(title)

      If Remove Then
        buffer = title[: 2]
        s.SetValue(buffer)
        If s.IsNumber() Then
          s.SetValue(title)

          While TRUE
            buffer = s.Left(1)
            Select Case buffer
            Case "a" To "z", "A" To "Z"
              Break
            Case Else
              If s.Len()= 0 Then Break
              s.SetValue(s.Right(s.Len() - 1))
            End Select
          Wend

        Else
          s.SetValue(title)
        End If
      End If

      Print #freenum, "#EXTINF: -1, " &s.GetData()
      Print #freenum, filePath
    Next

    dl = wxGenericMessageDialog(Nothing, _("The playlist was saved successfully."), _("Hint"), wxICON_INFORMATION|wxDIALOG_NO_PARENT)
    dl.ShowModal()

  Catch
    dl = wxGenericMessageDialog(Nothing, _("Error saving playlist file!"), _("Attention"), wxICON_WARNING|wxDIALOG_NO_PARENT)
    dl.ShowModal()

  Finally
    Close #freenum
    s.Clear()
    ~s
  End Try
End Sub


Sub onBrowseButtonClick(event As wxCommandEvent)
  Dim ctrl = DynamicCast("wxFilePickerCtrl", wxFindWindowByName("newFileName"))
  Dim fctrl = DynamicCast("wxGenericFileCtrl", wxFindWindowByName("batchFileCtrl"))
  Dim win As wxWindow = ctrl.GetParent()

  ctrl.SetValue(wxFileSelector( _("Choose a file:"), fctrl.GetDirectory(), wxFileNameFromPath(ctrl.GetPath()), "m3u", "*.m3u", wxFD_SAVE))
End Sub

