(ns il.core
  (:require [ring.adapter.jetty :as jetty]
            [ring.websocket.async :refer [go-websocket]]
            [compojure.core :as c]
            [compojure.route :as route]
            [clojure.core.async :refer [<! >! go-loop]]
            [clojure.data.json :as json]
            [il.world :as w]
            [il.constant :as consts]
            [hiccup.core :as h]))

(def world (-> {}
               (w/generate-water consts/world-width consts/world-height)
               (w/generate-resources
                consts/resources
                consts/min-resources
                consts/max-resources
                consts/world-width
                consts/world-height)))

(defn ws-handler [_]
  (go-websocket [in out err]
                (go-loop []
                  (when-let [e (<! err)]
                    (println (.getMessage e))
                    (recur)))
                (go-loop []
                  (if-let [msg (<! in)]
                    (do
                      (cond
                        (= msg "world") (>! out (json/write-str world)))
                      (println msg)
                      (recur))
                    (println "Closed.")))))

(defn index-handler [_]
  (h/html
   [:html
    [:head
     [:title "Ironlegacy"]
     [:style "* { margin: 0; padding: 0; } body { overflow: hidden; background: #1a2a1a; }"]
     [:div {:id "app"}]
     [:script {:src "/js/app.js" :defer true}]]
    [:body]]))

(c/defroutes app
  (c/GET "/" r (index-handler r))
  (c/GET "/ws" r (ws-handler r))
  (route/resources "/")
  (route/not-found "<h1>The requested resource does not exist...</h1>"))

(defn -main []
  (let [port 5000]
    (jetty/run-jetty
     app
     {:port port :join? true :max-idle-timeout 60000}))) ; Allow 60 second idle on websockets
