;;; app/twitter/autoload.el -*- lexical-binding: t; -*-

;;;###autoload
(defun +twitter-display-buffer (buf)
  "A replacement display-buffer command for `twittering-pop-to-buffer-function'
that works with the feature/popup module."
  (let ((win (selected-window)))
    (display-buffer buf)
    ;; This is required because the new window generated by `pop-to-buffer'
    ;; may hide the region following the current position.
    (twittering-ensure-whole-of-status-is-visible win)))

;;;###autoload
(defun +twitter-buffer-p (buf)
  "Return non-nil if BUF is a `twittering-mode' buffer."
  (eq 'twittering-mode (buffer-local-value 'major-mode buf)))


;;
;; Commands
;;

;;;###autoload
(defun =twitter ()
  "Opens a workspace dedicated to `twittering-mode'."
  (interactive)
  (condition-case _
      (progn
        (+workspace/new "*Twitter*")
        (call-interactively #'twit)
        (unless (get-buffer (car twittering-initial-timeline-spec-string))
          (error "Failed to open twitter"))
        (switch-to-buffer (car twittering-initial-timeline-spec-string))
        (dolist (name (cdr twittering-initial-timeline-spec-string))
          (split-window-horizontally)
          (switch-to-buffer name))
        (balance-windows)
        (call-interactively #'+twitter/rerender-all))
    ('error (+twitter/quit-all))))

;;;###autoload
(defun +twitter/quit ()
  "Close the current `twitter-mode' buffer."
  (interactive)
  (when (eq major-mode 'twittering-mode)
    (twittering-kill-buffer)
    (+workspace/close-window-or-workspace)))

;;;###autoload
(defun +twitter/quit-all ()
  "Close all open `twitter-mode' buffers and the associated workspace, if any."
  (interactive)
  (+workspace/delete "*Twitter*")
  (dolist (buf (doom-buffers-in-mode 'twittering-mode (buffer-list) t))
    (twittering-kill-buffer buf)))

;;;###autoload
(defun +twitter/rerender-all ()
  "Rerender all `twittering-mode' buffers."
  (interactive)
  (dolist (buf (doom-buffers-in-mode 'twittering-mode (buffer-list) t))
    (with-current-buffer buf
      (twittering-rerender-timeline-all buf)
      (setq-local line-spacing 0.2)
      (goto-line 0 buf))))