(in-package #:cl-user)

(defpackage #:cl-deck-builder2.app
  (:use #:cl)
  (:import-from #:mito-attachment
                #:*storage*
                #:s3-storage
                #:disk-storage
                #:disk-storage-mount-path)
  (:import-from #:lack.builder
                #:builder)
  (:import-from #:ppcre
                #:scan)
  (:import-from #:cl-deck-builder2.web
                #:*web*
                #:make-chat-server)
  (:import-from #:cl-deck-builder2.config
                #:config
		#:productionp
                #:*public-directory*
                #:*static-directory*)
  (:import-from #:cl-deck-builder2.toolkit
                #:git-revision)
  (:documentation "The package the app file executes in. Passed to ~CLACK:CLACKUP~ function."))

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

(defparameter *git-revision* (git-revision))

(setf *storage*
      (if (productionp)
          ;; Store files in AWS S3 for production environment
          (make-instance 's3-storage
                         :bucket "mito-attachment-example"
                         :endpoint "s3-ap-northeast-1.amazonaws.com"
                         :access-key (uiop:getenv "AWS_ACCESS_KEY")
                         :secret-key (uiop:getenv "AWS_SECRET_KEY"))
          ;; Store files in local filesystem for development environment
          (make-instance 'disk-storage
                         :bucket "mito-attachment-example"
                         :directory (merge-pathnames "attachment" *public-directory*))))

(builder
 (:static
  :path (lambda (path)
          (if (ppcre:scan "^(?:/img/|/css/|/js/|/webfonts/|/robot\\.txt$|/favicon\\.(ico|png)|/manifest\\.json$)" path)
              path
              nil))
  :root *static-directory*)
 (:static
  :path "/public/"
  :root *public-directory*)
 (if (productionp)
     nil
     :accesslog)
 (if (getf (config) :error-log)
     `(:backtrace
       :output ,(getf (config) :error-log))
     nil)
 :session
 :csrf
 (when (typep *storage* 'disk-storage)
   `(:mount ,(disk-storage-mount-path *storage*) ,*storage*))
 (:clack-errors :debug t)
 (if (productionp)
     nil
     (lambda (app)
       (lambda (env)
         (let ((datafly:*trace-sql* t))
           (setf (getf djula:*default-template-arguments* :git-revision) *git-revision*
                 (getf djula:*default-template-arguments* :server-name) "phntsm.ddns.net")
           (funcall app env)))))
 (:mount "/label-maker" cl-deck-builder2.web.label-maker:*web*)
 (:mount "/tinymce" cl-deck-builder2.web.tinymce:*web*)
 (:mount "/chat-server" #'cl-deck-builder2.web.sse:make-chat-server)
 *web*)
