;;; +emms.el --- EMMS customizations -*- lexical-binding: t; -*-

;;; Commentary:

;;; Code:

(require 'emms-player-mpv)
(require 'el-patch)

;; https://lists.gnu.org/archive/html/emms-help/2022-01/msg00006.html
(el-patch-feature emms-player-mpv)
(with-eval-after-load 'emms-player-mpv
  (el-patch-defun emms-player-mpv-start (track)
    (setq emms-player-mpv-stopped nil)
    (emms-player-mpv-proc-playing nil)
    (let
        ((track-name (emms-track-get track 'name))
         (track-is-playlist (memq (emms-track-get track 'type)
                                  '(streamlist playlist))))
      (if (emms-player-mpv-ipc-fifo-p)
          (progn
            ;; ipc-stop is to clear any buffered commands
            (emms-player-mpv-ipc-stop)
            (emms-player-mpv-proc-init (if track-is-playlist "--playlist" "--")
                                       track-name)
            (emms-player-started emms-player-mpv))
        (let*
            ((play-cmd
              `(batch
                ((,(el-patch-swap
                     (if track-is-playlist 'loadlist 'loadfile)
                     'loadfile)
                  ,track-name replace))
                ((set pause no))))
             (start-func
              ;; Try running play-cmd and retry it on connection failure, e.g. if mpv died
              (apply-partially 'emms-player-mpv-cmd play-cmd
                               (lambda (_mpv-data mpv-error)
                                 (when (eq mpv-error 'connection-error)
                                   (emms-player-mpv-cmd play-cmd))))))
          (if emms-player-mpv-ipc-stop-command
              (setq emms-player-mpv-ipc-stop-command start-func)
            (funcall start-func)))))))

(provide '+emms)
;;; +emms.el ends here
