#!/usr/bin/env bb

(require '[clojure.java.io :as io]
         '[clojure.string :as string]
         '[clojure.pprint :refer [pprint]])

(def exceptions
  #{"index.html"
    "styles.css"
    "js"
    "clapping.gif"
    "go.png"
    "clapping.png"
    "vendor"})

(let [foldername "./resources/public"
      folder (io/file foldername)
      existing-filename "./library.edn"
      existing (try
                 (-> existing-filename
                     (slurp)
                     (read-string))
                 (catch Exception _ []))
      existing-files (->> existing
                          (map :image)
                          (set))
      highest-index (or (some->> existing
                                 (map :id)
                                 (not-empty)
                                 (apply max)
                                 (inc))
                        1)]
  (if (.isDirectory folder)
    (->> (.list folder)
         (remove exceptions)
         (remove existing-files)
         (map-indexed (fn [ind file]
                        {:id (+ highest-index ind)
                         :name (-> file
                                   (string/replace #"\.[^\.]*$" "")
                                   (string/replace #"[-\._]" " "))
                         :image file}))
         (concat existing)
         (vec)
         ((fn [new-data]
            (with-open [writer (io/writer existing-filename)]
              (pprint new-data writer))
            (println "wrote to" existing-filename))))
    (println "Folder not found. Make sure to run this script from its containing folder.")))

