;; Integration with https://tools.sebasmonia.com/ website =D
(defun hoagie--pb-region-callback (request-status kill-paste-url)
  "Callback for requests from `hoagie-pb-region'.
Ignore the request status (first parameter), and KILL-PASTE-URL should
be self-explanatory."
  ;; I guess I should check the status code >_>
  (let ((paste-id (string-trim (buffer-substring url-http-end-of-headers
                                                 (point-max)))))
    (when kill-paste-url (kill-new
                          (concat "https://tools.sebasmonia.com/pb/"
                                  paste-id)))
    (message "Paste ID: %s" paste-id)))

(defun hoagie-pb-region (&optional kill-paste-url)
  "Create a Peanut Butter paste with the active region.
If KILL-PASTE-URL is non-nil (interactively, prefix arg) then place the
paste URl in the kill ring."
  (interactive "P")
  (if (not (use-region-p))
      (error "No active region")
    (let ((url-request-method "PUT")
          (url-request-data (buffer-substring-no-properties
                             (region-beginning) (region-end))))
      (url-retrieve "https://tools.sebasmonia.com/pb"
                    #'hoagie--pb-region-callback
                    (list kill-paste-url)))))

(defun hoagie-sol-add-link (url title)
  "Add a new link in my stack of links."
  (interactive "sURL: \nsTitle (empty to fetch): ")
  (if-let* ((api-key (getenv "X-HOAGIE-KEY"))
            (url-request-method "POST")
            (url-request-extra-headers
             (list (cons "x-hoagie-key" api-key)
                   (cons "Content-Type" "application/x-www-form-urlencoded")))
            (url-request-data (concat "link="
                                      (url-hexify-string url)
                                      (when title
                                        (concat "&title="
                                                (url-hexify-string title))))))
      (with-current-buffer
          (url-retrieve-synchronously "https://tools.sebasmonia.com/sol/add"
                                      t)
        (message (string-trim (buffer-substring url-http-end-of-headers
                                                (point-max)))))
    (error "X-HOAGIE-KEY is not set")))