 (ns hellhound.tasks.db
-  (:require [hellhound.tasks.core :refer [in-migrations]]
+  (:require [hellhound.tasks.core :refer [in-migrations epoch-time long-str info error warn]]
             [clojure.string       :refer [ends-with? starts-with?]]
-            [clj-time.core        :refer [before?]]))
+            [clojure.edn          :as edn]
+            [clj-time.core        :refer [before?]]
+            [clojure.java.io :as io]))
 
+;; DEFINATIONS
 
-(defn long-str [& strings] (clojure.string/join "\n" strings))
+;; Lock is not a great name i know, but i don't have
+;; time to think about it
+(def migrations-lock (atom []))
+(def migration-lock-file (io/resource "migration.lock"))
 (def migration_template
   (long-str "(ns db.migrations.%s)"
             ""

            "  []"
            "  ;; Your code to teardown this migration, goes here"
            ")"))

(defn- is-timestamp?
  [value]

         (filter (fn [x] (println (ns-name x)) (starts-with? (ns-name x) "db.migrations")))
         (sort #(before? (timestamp %1) (timestamp %2))))))

(defn migrate
  [& rest]
  (let [migrations @migrations-lock]
    (if (empty? migrations)
      (warn "No migration found")
      (doseq [migration migrations]
        (println migration)))))

(defn new-migrate
  [name & rest]
  (let [epoch     (epoch-time)
        nsname    (str epoch "_" name)
        file-path (in-migrations (str nsname ".clj"))]
    (info "Creating migration file: " file-path)
    (spit file-path
          (format migration_template nsname))
    (info "Updating migrations lock file")
    (update-lock nsname)))

(defn wrong-command
  [cmd]
  (error (format "Can't find the command '%s'." cmd)))

(defn -main
  [command & rest]
  (get-lock)
  (cond
    (= command "migration") (apply new-migrate rest)
    (= command "migrate")   (apply migrate rest)
