#|

src/web/toolkit.lisp

Helper Functions - Web Toolkit

TODO move to src/toolkit/web.lisp ?

TODO Packaging up and exporting macros seems to be a bad idea, it
causes some kind of symbol errors. Maybe we need to be using the full
name of each thing in a defmacro? I feel like taichi would say don't
use a macro at all.

|#

(in-package #:cl-deck-builder2.web)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter *md2html* "/usr/lib/cgit/filters/html-converters/md2html")

(defmacro with-logged-in-user (&body body)
  `(progn
     ;; (v:info :web "~a" caveman2:*request*)
     ;;
     ;; Store the current REQUEST-PATH-INFO
     ;;
     ;; We lose the query parameters when we do it this way. Problem? Not sure.
     ;;
     ;; (setf (gethash :request-query-parameters caveman2:*session*)
     ;;       (lack.request:request-query-parameters caveman2:*request*))
     (setf (gethash :request-path-info caveman2:*session*)
           (lack.request:request-path-info caveman2:*request*))
     (if (logged-in-p)
         (progn
           ,@body)
         (progn
           (flash-error (_ "Please log in."))
           (redirect "/user/login")))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun render-with-env (tpl &optional lst)
  "Helper macro: APPEND some variables to ENV list passed to RENDER."
  (render tpl
   (append lst
    `(:messages ,(flash-gethash)
      :session ,*session*
      :token ,(token)
      :is-admin ,(ignore-errors
                  (user-admin-p 
                   (find-user (user-name))))
      :is-verified ,(ignore-errors
                     (user-verified-p 
                      (find-user (user-name))))
      :csrf_token ,(lack.middleware.csrf:csrf-token *session*)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun render-markdown (pathspec &key env title (tpl #P"markdown.html"))
  "Render Markdown Page with template TPL"
  (alexandria:if-let ((path (probe-file pathspec)))
    (alexandria:if-let ((html (render-markdown-file pathspec)))
      (render-with-env tpl
                       (append env
                               (list :title title :html html))))))

(defun render-markdown-file (pathspec)
  "Wrap md2html from cgit installation."
  (with-output-to-string (s)
    (uiop:run-program *md2html*
                      :output s
                      :input pathspec)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun token ()
  "Helper function: get the CSRF token associated with this *REQUEST*."
  ;; (cdr (assoc "lack.session" (request-cookies *request*)
  ;;             :test #'string=))
  ;; https://40ants.com/lisp-project-of-the-day/2020/06/0113-lack-middleware-csrf.html
  (lack.middleware.csrf:csrf-html-tag *session*))
