(in-package :cl-user)

(defpackage #:cl-deck-builder2.view
  (:use #:cl)
  (:import-from #:cl-deck-builder2.config
                #:*template-directory*)
  (:import-from #:cl-deck-builder2.i18n
                #:with-locale)
  (:import-from #:caveman2
                #:*response*
                #:response-headers)
  (:import-from #:djula
                #:add-template-directory
                #:compile-template*
                #:render-template*
                #:*djula-execute-package*)
  (:import-from #:datafly
                #:encode-json)
  (:export #:render
           #:render-json)
  (:documentation "The VIEW package.

We just use the defaults generated by Caveman2.

It provides rendering functions for web view.

Additionally, we have i18n support with gettext."))

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

(djula:add-template-directory *template-directory*)

(defparameter *template-registry* (make-hash-table :test 'equal)
  "Hash table of registered templates. Used for caching.")

(defun render (template-path &optional env (lang "en_US"))
  "Use Djula to render a template."
  (let ((template (gethash template-path *template-registry*)))
    (unless template
      (setf template (djula:compile-template* (princ-to-string template-path)))
      (setf (gethash template-path *template-registry*) template))
    (with-locale (lang)
      (apply #'djula:render-template* template nil env))))

(defun render-json (object)
  "Use Datafly to render a JSON object."
  (setf (getf (response-headers *response*) :content-type) "application/json")
  (encode-json object))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Execute package definition

(defpackage #:cl-deck-builder2.djula
  (:use :cl)
  (:import-from :cl-deck-builder2.config
                :config
                :appenv
                :developmentp
                :productionp)
  (:import-from :caveman2
                :url-for)
  (:documentation "The package in which template expressions are evaluated.

SEE <https://quickref.common-lisp.net/djula.html#g_t_276866_2769>"))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setf djula:*djula-execute-package* (find-package :cl-deck-builder2.djula))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package #:djula)

(djula:def-filter :describe (it)
  (with-output-to-string (s) (describe it s)))
