#|

src/web/index.lisp

Some static top-level routes.

If there isn't much to the page it probably appears here e.g. / /about /news

|#

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

(defroute index "/" ()
  "Main HTML index."
  (with-logged-in-user
    (render-with-env #P"index.html" `(:active "/"))))

;; (render-markdown
;;  (relative-pathname "doc/index.md")
;;  :title "Index" :env `(:active "/index"))

(defroute "/about" ()
  "About page."
  (with-logged-in-user
    (render-markdown
     (relative-pathname "doc/about.md")
     :title "About" :env `(:active "/about"))))

(defroute "/news" ()
  "News page. We use parse git log in toolkit/git.lisp."
  (with-logged-in-user
    (render-with-env #P"news.html"
                     `(:active "/news"
                       :git-log ,(mapcar #'parse-git-log (git-log))))))

(defroute ("/todo" :method :GET) ()
  "To-Do list page. This is my personal professional todo list!"
  (with-logged-in-user
    (render-markdown
     (asdf:system-relative-pathname :cl-deck-builder2
                                    "doc/todo.md")
     :title "To-Do List"
     :env `(:active "/todo"))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defroute ("/markdown" :method :GET) (&key _parsed)
  "A utility URL to parse markdown files.

In a production environment you would probably want to disable this URL, as it could potentially allow an attacker to read arbitrary source files. That isn't a concern since we're running in a Docker container."
  (with-logged-in-user
    (let* ((path (query-param "path" _parsed))
           (pathspec (asdf:system-relative-pathname :cl-deck-builder2 path)))
      (alexandria:if-let ((extracted-title (ignore-errors
                                            (car (uiop:read-file-lines pathspec)))))
        (render-markdown pathspec :title extracted-title)
        (render-with-env #P"markdown.html" (list :title "Oops!" :html "Nothing to see here..."))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun extract-router-docs (app)
  "Courtesy of knobo: https://github.com/fukamachi/caveman/pull/108"
  (sort
   (mapcar (lambda (route)
             (list
              (myway.rule::rule-url (myway.route:route-rule route))
              (documentation (ningle.route:route-controller route) 'function)
              (car (map-set:ms-map 'list 'identity (myway.rule::rule-methods (myway.route:route-rule route))))
              (myway.rule::rule-param-keys (myway.route:route-rule route))))
           (myway:mapper-routes (ningle.app::mapper app)))
   #'string<
   :key #'car))

(defroute doc "/doc" (&key |org|)
  "This url shows this the documentation."
  (with-logged-in-user
    (let ((docs (extract-router-docs *web*))
          (tpl (if |org|
                   #P"docs.md"
                   #P"docs.html")))
      (render-with-env tpl
                       `(:active "/doc"
                         :docs ,docs)))))
