;;; jao-doc-session.el --- persistent document sessions  -*- lexical-binding: t; -*-

;; Copyright (C) 2022, 2024, 2025, 2026  jao

;; Author: jao <mail@jao.io>
;; Keywords: docs

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Code:

(require 'multisession)

(define-multisession-variable jao-doc--session nil)

(defun jao-doc-session () (multisession-value jao-doc--session))

(defvar-local jao-doc-session-is-doc nil
  "Locally marks a buffer as belonging to a session.

See also `jao-doc-session-mark'.")

(defun jao-doc-session-is-doc (&optional buffer)
  "Check whether the given or current buffer belong to the doc session."
  (buffer-local-value 'jao-doc-session-is-doc (or buffer (current-buffer))))

(defun jao-doc-session-save (&optional skip-current force)
  "Traverse all current buffers and update the value of `jao-doc-session'."
  (interactive)
  (let ((docs '())
        (cb (and skip-current (current-buffer))))
    (dolist (b (buffer-list))
      (when-let* ((fs (and (not (eq cb b)) (jao-doc-session-is-doc b)))
                  (fs (if (listp fs) fs (list (buffer-file-name b)))))
        (dolist (f fs) (add-to-list 'docs f))))
    (when (or force (> (length docs) 0))
      (setf (multisession-value jao-doc--session) docs))))

(defun jao-doc-session-mark (&optional path)
  "Mark the current buffer's file, or PATH, as persistent across sessions."
  (unless (listp jao-doc-session-is-doc)
    (setq jao-doc-session-is-doc (ensure-list jao-doc-session-is-doc)))
  (cl-pushnew (or path (buffer-file-name)) jao-doc-session-is-doc)
  (jao-doc-session-save))

(defun jao-doc-session--maybe-save ()
  (when (jao-doc-session-is-doc) (jao-doc-session-save t)))

(add-hook 'kill-buffer-hook #'jao-doc-session--maybe-save)
(add-hook 'kill-emacs-hook #'jao-doc-session-save)

(provide 'jao-doc-session)
;;; jao-doc-session.el ends here
