(ns wanijo.visualisation.routes
  (:require [compojure.core :refer [defroutes wrap-routes
                                    GET POST DELETE]]
            [wanijo.infrastructure
             [routing :refer [register! path]]
             [view :as view]]
            [wanijo.instance.db :as db-instance]
            [wanijo.schema.db :as domain-schema]
            [wanijo.visualisation
             [db :as vis-db]
             [viz :as viz]
             [view :as vis-view]]))

(defn all-instances [req]
  (view/layout
    :request req
    :content
    [[:h1 "All Instances"]
     (viz/all-instances (vis-db/all-instance-connections!))]))

(defn all-schemas [req]
  {:content-type "text/json"
   :body (domain-schema/accessible-schemas! (-> req :session :uuid))})

(defn instance [uuid]
  {:content-type "text/json"
   :body (vis-db/instance! uuid)})

(defn search [term]
  {:content-type "text/json"
   :body (map #(merge %
                      {:urls {:instance (path :vis-get-instance %)}})
              (vis-db/search! term))})

(defroutes routes
  (GET (register! :vis-explore "/vis/explore/:instance-uuid")
       [instance-uuid :as req]
       (vis-view/index (db-instance/find-by-uuid! instance-uuid)
                       req))
  (GET (register! :vis-all-instances "/vis/all-instances")
       [:as req]
       (all-instances req))
  (GET (register! :vis-all-schemas "/api/vis/schemas")
       [:as req]
       (all-schemas req))
  (GET (register! :vis-get-instance "/api/vis/instance/:uuid")
       [uuid]
       (instance uuid))
  (GET (register! :vis-search-instance "/api/vis/search/:term")
       [term]
       (search term)))
