diff --git a/src/packer/main.clj b/src/packer/main.clj index 4894185..635bffe 100644 --- a/src/packer/main.clj +++ b/src/packer/main.clj @@ -51,7 +51,7 @@ :else (let [script (last (eval-file template-file)) i18n (:i18n script) - nights (util/ask-int (:nights? i18n)) + nights (util/ask-nights (:nights? i18n) (:start-date? i18n) (:end-date? i18n)) store (:store script) profile ((:profile script) nights)] (spit output-file (str (core/produce store profile nights i18n) "\n")))))) \ No newline at end of file diff --git a/src/packer/util.clj b/src/packer/util.clj index ef6bfc6..7b4fe5f 100644 --- a/src/packer/util.clj +++ b/src/packer/util.clj @@ -1,5 +1,9 @@ (ns packer.util (:gen-class)) +(import '(java.time.temporal ChronoUnit) + '(java.time LocalDate) + '(java.time.format DateTimeFormatter)) + (defn ask ([question prompt] (print (str question prompt)) (flush) @@ -20,4 +24,26 @@ (let [answer (clojure.string/lower-case (ask question " (y/n) \u2192 "))] (if (.contains "yn" answer) (= "y" answer) - (recur question)))) \ No newline at end of file + (recur question)))) + +(defn parse-date [date] + (let [now (LocalDate/now) + parts (into [] (map #(format "%02d" (Integer/parseInt %)) (clojure.string/split date #"\W"))) + formatter (DateTimeFormatter/ofPattern "dd-MM-yyyy") + month (String/format "%02d" (into-array Integer [(.getMonthValue now)])) + year (.toString (.getYear now)) + full-date (case (count parts) + 1 (str (parts 0) "-" month "-" year) + 2 (str (parts 0) "-" (parts 1) "-" year) + 3 (str (parts 0) "-" (parts 1) "-" (parts 2)) + (throw (Exception. (str "Invalid date format: " date))))] + (LocalDate/parse full-date formatter))) + +(defn count-nights [start end] + (.between ChronoUnit/DAYS (parse-date start) (parse-date end))) + +(defn ask-nights [nightsQuestion startQuestion endQuestion] + (let [start (ask startQuestion) + end (when (not (empty? start)) (ask endQuestion)) + nights (when (empty? start) (ask-int nightsQuestion))] + (if (empty? start) nights (count-nights start end)))) \ No newline at end of file