(ns script
  (:require [babashka.fs :as fs]
            [babashka.cli :as cli]
            [babashka.process :refer [sh]]))

(def target-height 480)


(def cli-spec
  {:spec
   {:input-dir {:coerce :string
          :desc "input directory"
          :alias :i                     ; adds -n alias for --num
          :validate fs/directory?
          :require true}                ; --num,-n is required
    :output-dir {:desc "file"
                  :alias :o
                  :validate fs/directory?}        ; tests if --dir exists
    :skip {:desc "how many files to skip"
          :alias :s
          :coerce :long
           :default 0}
    :nth {:desc "every nth file"
          :alias :n
          :coerce :long
          :default 1}
    :flag {:coerce :boolean             ; defines a boolean flag
           :desc "I am just a flag"}}
   :error-fn                           ; a function to handle errors
   (fn [{:keys [spec type cause msg option] :as data}]
     (if (= :org.babashka/cli type)
       (case cause
         :require
         (println
          (format "Missing required argument: %s\n" option))
         :validate
         (println
          (format "%s does not exist!\n" msg)))))
   :args->opts [:input-dir :output-dir]})

(let [options (cli/parse-opts *command-line-args* cli-spec)
      _ (sh "mkdir" "-p" (:output-dir options))
      source-files (->> (fs/list-dir (:input-dir options)) 
                        (filter (fn [f] (= "png" (fs/extension f))))
                                (sort)
         (drop (:skip options))
         (partition-all (:nth options))
         (map first)
                                (map str))]
    (println "processing:")
    (clojure.pprint/pprint source-files)
    (doseq [[n sf] (map vector (range) source-files)] 
      (sh "convert" sf 
          "-unsharp" "0.5x1+0.7+0.02%" 
          "-resize" (str "x" target-height) 
          "-filter" "Lanczos"
          (fs/path (:output-dir options) (format "%04d .png" n )))))

#_(let [input-file (nth *command-line-args* 0)
      output-file (nth *command-line-args* 1)]
  )
