   "Celestial systems api"
   (:refer-clojure :exclude [type])
   (:require 
+    [celestial.security :refer (current-user)]
+    [ring.util.codec :refer (base64-decode)]
+    [clojure.data.json :as json]
     [celestial.persistency :as p]
     [cemerick.friend :as friend]
     [celestial.persistency.systems :as s]
+    [es.systems :as es]
     [celestial.model :refer (sanitized-envs)] 
     [clojure.core.strint :refer (<<)] 
     [slingshot.slingshot :refer  [throw+ try+]] 


  (DELETE- "/systems/:id" [^:int id] {:nickname "deleteSystem" :summary "Delete System" 
                                          :errorResponses (errors {:bad-req "System does not exist"})}
           (try+ 
             (let [spec (s/get-system! id) int-id (Integer/valueOf id)]               
               (s/delete-system! id) 
               (success {:message "System deleted"})) 

    (let [page* (Integer/valueOf page) offset* (Integer/valueOf offset)]
      (success (systems-range (* (- page* 1) offset*) (* page*  offset*)))))

  (GET- "/systems/query" [^:int page ^:int offset ^:query query]
      {:nickname "getSystemsBy" :summary "Get all systems at page with offset by query"}
    (let [page* (Integer/valueOf page) offset* (Integer/valueOf offset) 
          query-m (json/read-str (String. (base64-decode query)) :key-fn keyword)
          {:keys [hits]} (es/systems-for (working-username) {:bool query-m} (- page* 1)  offset*)]
      (success 
        {:meta {:total (:total hits)} 
         :systems (doall (map (juxt identity s/get-system) (map :_id (:hits hits))))})))

  (GET- "/systems/:id" [^:int id] {:nickname "getSystem" :summary "Get system by id"}
        (success (s/get-system id)))
