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

(require 'jao-org-notes)
(require 'jao-doc-view)
(require 'jao-doc-session)
(require 'jao-pdf)

(defvar jao-org--sink-dir "./")
(defvar jao-org-open-pdf-fun #'jao-org--default-open)

(defun jao-org--default-open (path page &optional height)
  (org-open-file path 1)
  (jao-doc-view-goto-page page height))

(defun jao-org--pdf-open (path page &optional height)
  (when (file-exists-p path) (jao-doc-session-mark path))
  (funcall (or jao-org-open-pdf-fun #'jao-org--default-open) path page height))

(defun jao-org-links--open-pdf (link)
  "Open LINK in pdf-view-mode."
  (cond ((string-match "\\(.*\\)::\\([0-9]*\\)\\+\\+\\([[0-9]\\.*[0-9]*\\)"  link)
         (let* ((path (match-string 1 link))
                (page (string-to-number (match-string 2 link)))
                (height (string-to-number (match-string 3 link))))
           (jao-org--pdf-open path page height)))
        ((string-match "\\(.*\\)::\\([0-9]+\\)$"  link)
         (let* ((path (match-string 1 link))
                (page (max 1 (string-to-number (match-string 2 link)))))
           (jao-org--pdf-open path page)))
        (t (jao-org--pdf-open link nil))))

(defun jao-org-links--follow-doc (link)
  (let* ((full-link (concat org-directory "/doc/" link))
         (dest-path (car (split-string full-link "::"))))
    (when (not (file-exists-p dest-path))
      (let* ((sink-file (expand-file-name link jao-org--sink-dir))
             (real-file (if (file-exists-p sink-file) sink-file
                          (read-file-name "Import file: "
                                          jao-org--sink-dir link link))))
        (rename-file real-file dest-path)))
    (if (jao-pdf-is-pdf-file dest-path)
        (jao-org-links--open-pdf full-link)
      (browse-url (format "file://%s" (expand-file-name  dest-path))))))

(defun jao-org-links--complete-doc (&optional arg)
  (let ((default-directory jao-org--sink-dir))
    (let ((f (replace-regexp-in-string "^file:" "doc:"
                                       (org-file-complete-link arg))))
      (if (jao-pdf-is-pdf-file f)
          (let ((page (read-from-minibuffer "Page: " "")))
            (if (> (string-to-number page) 0)
                (concat f "::" (read-from-minibuffer "Page: " ""))
              f))
        f))))

;;;###autoload
(defvar jao-org-links-pdf-store-fun nil)

(defun jao-org-links--store-pdf-link ()
  (or (when (fboundp jao-org-links-pdf-store-fun)
        (funcall jao-org-links-pdf-store-fun))
      (when (derived-mode-p 'pdf-view-mode 'doc-view-mode)
        (jao-org-links-store-pdf-link buffer-file-name
                                      (jao-doc-view-current-page)
                                      (jao-pdf-section-title)))))

;;;###autoload
(defun jao-org-links-store-pdf-link (path page title)
  (org-link-store-props
   :type "doc"
   :link (format "doc:%s::%d" (file-name-nondirectory path) page)
   :description (format "%s (p. %d)" title page)))

;;;###autoload
(defun jao-org-insert-doc (title)
  (interactive "sDocument title: ")
  (insert (format "[[doc:%s][%s]]" (jao-pdf-title-to-file-name title) title)))

;;;###autoload
(defun jao-org-open-from-zathura (title &optional no-ask)
  (when-let* ((info (jao-pdf-zathura-file-info title))
              (pdf-file (car info))
              (page (cadr info))
              (file (jao-org-notes-find-for-pdf pdf-file)))
    (jao-afio-goto-docs)
    (let ((exists (file-exists-p file)))
      (find-file file)
      (unless exists (jao-org-insert-doc-skeleton))
      (let ((lnk (jao-pdf--zathura-link info)))
        (jao-doc-session-mark)
        (if (or (not exists) (and (not no-ask) (y-or-n-p "Insert link?")))
            (insert lnk "\n")
          (kill-new lnk)
          (message "Link to %s (%s) killed" file page))))))

;;;###autoload
(defun jao-org-insert-doc-skeleton (&optional title)
  (insert "#+title: " (or title (jao-pdf-title (buffer-file-name)))
          "\n#+author:\n#+filetags: ")
  (jao-org-notes-insert-tags)
  (insert  "\n#+startup: latexpreview\n\n"))

;;;###autoload
(defun jao-org-pdf-goto-org (arg)
  (interactive "P")
  (when (jao-pdf-is-pdf-file buffer-file-name)
    (let* ((file (jao-org-notes-find-for-pdf))
           (new (not (file-exists-p file)))
           (title (jao-pdf-title)))
      (when (or arg new) (org-store-link nil t))
      (find-file-other-window file)
      (when new
        (jao-org-insert-doc-skeleton title)
        (org-insert-link)))))

;;;###autoload
(defun jao-org-pdf-goto-org* () (interactive) (jao-org-pdf-goto-org t))

;;;###autoload
(defun jao-org-goto-pdf ()
  (interactive)
  (if-let (f (jao-org-org-to-pdf-file))
      (jao-org--pdf-open f nil)
    (user-error "No PDF file associated with this buffer")))

(with-eval-after-load "org"
  (define-key org-mode-map (kbd "C-c o") #'jao-org-goto-pdf))

;;;###autoload
(defun jao-org-links-setup (sink-dir)
  (interactive)
  (org-link-set-parameters "doc"
                           :follow #'jao-org-links--follow-doc
                           :complete #'jao-org-links--complete-doc
                           :store #'jao-org-links--store-pdf-link)
  (org-link-set-parameters "docview" :store #'ignore)
  (setq jao-org--sink-dir (file-name-as-directory sink-dir)))

(provide 'jao-org-links)