 (ns lambda-blog.generator
+  "Filesystem utilities used in the generation pipeline."
   (:refer-clojure :exclude [update])
   (:require [clojure.java.io :refer [make-parents]]
             [lambda-blog.utils :refer [pathcat]]

            [s-html.print :refer [html->str]]
            [taoensso.timbre :as log]))

(defn copy-dir! [{:keys [output-dir] :as ent} what where]
  (let [to (pathcat output-dir where)]
    (log/info "Copying" what "to" to)
    (fs/copy-dir what to)
    ent))

(defn clean-dir! [{:keys [output-dir] :as ent}]
  (let [d (pathcat output-dir)]
    (log/info "Cleaning" d)
    (fs/delete-dir d)
    ent))

(defn update [entity key & funs]
  (assoc entity
         key ((reduce comp (reverse funs))
              (entity key))))

(defn update-all [entity key & funs]
  (let [vs (entity key)]
    (assoc entity
           key

         html->str
         (spit-file f))))

(defn generate!
  "Transforms a part of an `entity` under `key` into an HTML page using `template` with extra `args`. Returns unmodified `entity`, but interacts with the filesystem."
  [entity key template & args]
  (do-generate! template (merge entity (entity key)) args)
  entity)

(defn generate-all!
  "Transforms a sequence of values of an `entity` under `key` into HTML pages using `template` with extra `args`. Returns `entity` unmodified, but interacts with the filesystem."
  [entity key template & args]
  (doseq [ent (entity key)]
    (do-generate! template (merge entity ent) args))
  entity)

(defn read-dir
  "Reads a directory under `path` and parses each file using `parser`. Returns `entity` with parsed file contents sequence stored under `key`."
  [entity key path parser]
  (->> path
       fs/list-dir
       (map (fn [file]
              (log/info "Reading " file)
              (parser (slurp file))))
       (assoc entity key)))
