   "Systems indexing/searching"
   (:refer-clojure :exclude [get])
   (:require 
+    [clojure.set :refer (subset?)]
     [clojure.core.strint :refer (<<)] 
     [slingshot.slingshot :refer  [throw+]] 
     [es.node :as node]

   [query]
  (update-in query [:bool :should] (fn [ts] (mapv env-term ts))))

(defn envs-set 
  "set should envs" 
  [q {:keys [envs username]}]
  (let [q-envs (into #{} (filter identity (map #(keyword (get-in % [:term :env])) (get-in q [:bool :should]))))] 
    (if-not (empty? q-envs) 
      (if (clojure.set/subset? q-envs (into #{} envs)) 
         (map-env-terms q)
        (throw+ {:type ::non-legal-env :message (<< "~{username} tried to query in ~{q-envs} he has access only to ~{envs}")}))
      (update-in q [:bool :should] (fn [v] (into v (mapv #(hash-map :term {:env (str %)}) envs)))))))

(defn- query-for [username q]
  (let [{:keys [envs username] :as user} (p/get-user! username)]

(defn initialize 
  "Creates systems index and type" 
  []
  (node/start-n-connect [index])
  (when-not (idx/exists? index)
    (info "Creating index" index)
    (idx/create index :mappings system-types)))
