;; -*- lexical-binding: t; -*-

(require 'syd/base)
(require 'syd/hide-mode-line)

(defvar syd-new-popup-hook nil
  "Ran upon display of a new popup buffer.  The current buffer will be the
popup.  This differs from `popper-open-popup-hook' in that the hooks
are only ran *a single time* upon the buffer's first time being
displayed, rather than each time it is displayed.")

(defvar syd-help-popup-options
  '(:select t :size 0.42 :popup t :align bottom))

(use-package shackle
  :hook on-init-ui
  :custom ((shackle-default-size 0.33))
  :config
  (syd-push shackle-rules
            `("*Help*" ,@syd-help-popup-options)
            '("*Messages*" :select t :size 0.16 :popup t :align bottom))
  (defvar-local syd--new-popup-hook-ran nil)
  (syd-defadvice syd--shackle-run-new-popup-hook-a (buffer _alist)
    :after #'shackle-display-buffer-action
    (unless syd--new-popup-hook-ran
      (with-current-buffer buffer
        (run-hooks 'syd-new-popup-hook))
      (setq syd--new-popup-hook-ran t))))

(use-package popper
  :hook on-init-ui
  :init
  (require 'shackle)
  (setq popper-display-control nil
        popper-reference-buffers (list #'shackle-match))
  :config
  ;; Close on escape.
  (syd-add-hook 'syd-escape-hook
    (defun syd-escape-close-popups-h ()
      "If the current buffer is a popup, close it.  Otherwise, close all popups."
      (if (popper-popup-p (current-buffer))
          (popper-close-latest)
        (while popper-open-popup-alist
          (popper-close-latest)))))
  (syd-add-hook 'kill-buffer-hook
    (defun syd-popups--kill-buffer-hook-h ()
      "Delete the window of a killed popup buffer."
      (when-let* ((window (get-buffer-window)))
	(when (eq popper-popup-status 'popup)
	  (delete-window window)))))
  (add-hook 'syd-new-popup-hook #'hide-mode-line-mode))

(provide 'syd/popups)
