(ns yenu.core
  (:require [yenu.handler :as handler]
            [luminus.repl-server :as repl]
            [luminus.http-server :as http]
            [luminus-migrations.core :as migrations]
            [yenu.config :refer [env]]
            [clojure.tools.logging :as log]
            [yenu.helpers.images :as image]
            [mount.core :as mount])
  (:gen-class))

(mount/defstate ^{:on-reload :noop}
  http-server
  :start
  (http/start
   (-> env
       (assoc :handler (handler/app))
       (update :port #(or (-> env :options :port) %))))
  :stop
  (http/stop http-server))

(mount/defstate ^{:on-reload :noop}
  repl-server
  :start
  (when-let [nrepl-port (env :nrepl-port)]
    (repl/start {:port nrepl-port}))
  :stop
  (when repl-server
    (repl/stop repl-server)))


(defn stop-app []
  (doseq [component (:stopped (mount/stop))]
    (log/info component "stopped"))
  (shutdown-agents))

(defn start-app [args]
  (doseq [component (-> args
                        mount/start-with-args
                        :started)]
    (log/info component "started"))
  (.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)))

(defn setup-prerequisites []
  (image/create-needed-folders)
  (migrations/migrate ["migrate"] (select-keys env [:database-url])))

(defn -main [& args]
  (mount/start #'yenu.config/env)
  (setup-prerequisites)
  (start-app args))
