(ns auto-ap.server
  (:require [auto-ap.handler :refer [app]]
            [auto-ap.ledger :as ledger]
            [auto-ap.yodlee.core]
            [auto-ap.yodlee.core2 :as yodlee2]
            [auto-ap.graphql.clients :as gq-clients]
            [auto-ap.background.invoices]
            [auto-ap.background.vendor :as vendor]
            [auto-ap.square.core :as square]
            [auto-ap.datomic.migrate :as migrate]
            [auto-ap.yodlee.import :as yodlee]
            [nrepl.server :refer [start-server stop-server]]
            [config.core :refer [env]]
            [ring.adapter.jetty :refer [run-jetty]]
            [clojure.tools.logging :as log]
            [unilog.config]
            [mount.core :as mount])
  (:gen-class))

(defn add-shutdown-hook! [^Runnable f]
  (.addShutdownHook (Runtime/getRuntime)
                    (Thread. f)))

(mount/defstate port :start (Integer/parseInt (or (env :port) "3000")))
(mount/defstate jetty
  :start (run-jetty app {:port port :join? false})
  :stop (.stop jetty))

(defn shutdown-mount []
  (mount/stop))

 (defn -main [& args]
   (let [without  (cond-> []
                    (not (env :run-web? )) (into [#'jetty])
                    (not (env :run-background?)) (into [#'square/square-loader
                                                        #'vendor/refresh-vendor-usages-worker
                                                        #'ledger/touch-broken-ledger-worker
                                                        #'ledger/process-txes-worker
                                                        #'ledger/ledger-reconciliation-worker
                                                        #'auto-ap.background.invoices/close-auto-invoices-worker
                                                        #'gq-clients/current-balance-worker
                                                        #'yodlee/import-transaction-worker
                                                        #'yodlee2/yodlee-sync-worker
                                                        #'migrate/migrate-start]))]
     (log/info "starting without " without)
     
     (add-shutdown-hook! shutdown-mount)
     (start-server :port 9000 :bind "0.0.0.0" #_#_:handler (cider-nrepl-handler))
     (apply mount/start-without without)))
