;;; +eww.el -*- lexical-binding: t; -*-

;;; Code:

(require 'bookmark)
(require 'eww)

;; Track whether the current page is readable

(defvar-local +eww-readable-p nil
  "Whether `eww-readable' has been toggled on the current buffer.")

(defun +eww-mark-readable (&rest _)
  "ADVICE to mark current eww buffer \"readable.\""
  (setq-local +eww-readable-p t))

(defun +eww-mark-unreadable (&rest _)
  "ADVICE to mark current eww buffer \"unreadable.\""
  (setq-local +eww-readable-p nil))

(defvar +eww-readable-unreadable-after-functions '(eww-render
                                                   eww-reload
                                                   eww-back-url)
  "Functions after which the page is rendered \"unreadable\".")

;;;###autoload
(define-minor-mode +eww-track-readable-mode
  "Track whether the current webpage has been rendered readable."
  :lighter ""
  (if +eww-track-readable-mode
      (progn
        (advice-add 'eww-readable :after #'+eww-mark-readable)
        (dolist (func +eww-readable-unreadable-after-functions)
          (advice-add func :after #'+eww-mark-unreadable)))
    (dolist (func +eww-readable-unreadable-after-functions)
      (advice-remove func #'+eww-mark-unreadable))
    (advice-remove 'eww-readable #'+eww-mark-readable)))

;; Integrate bookmarks in eww

(defun +eww-bookmark--make ()
  "Make eww bookmark record."
  `((filename . ,(plist-get eww-data :url))
    (title . ,(plist-get eww-data :title))
    (time . ,(current-time-string))
    (handler . ,#'+eww-bookmark-handler)
    (defaults . (,(concat
                   ;; url without the https and path
                   (replace-regexp-in-string
                    "/.*" ""
                    (replace-regexp-in-string
                     "\\`https?://" ""
                     (plist-get eww-data :url)))
                   " - "
                   ;; page title
                   (replace-regexp-in-string
                    "\\` +\\| +\\'" ""
                    (replace-regexp-in-string
                     "[\n\t\r ]+" " "
                     (plist-get eww-data :title))))))))

(defun +eww-bookmark-handler (bm)
  "Handler for eww bookmarks."
  (eww-browse-url (alist-get 'filename bm)))

(defun +eww-bookmark-setup ()
  "Setup eww bookmark integration."
  (setq-local bookmark-make-record-function #'+eww-bookmark--make))

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