<commit_before>(ns akvo.lumen.lib.visualisation.maps
  (:require [akvo.lumen.lib :as lib]
            [akvo.lumen.lib.aggregation.filter :as filter]
            [akvo.lumen.lib.visualisation.map-config :as map-config]
            [akvo.lumen.lib.visualisation.map-metadata :as map-metadata]
            [akvo.lumen.util :as util]
            [cheshire.core :as json]
            [clj-http.client :as client]
            [hugsql.core :as hugsql]))

(hugsql/def-db-fns "akvo/lumen/lib/dataset.sql")

(defn- headers [uri]
  (let [{:keys [password user]} (util/query-map (.getQuery uri))
        port (let [p (.getPort uri)]
               (if (pos? p) p 5432))]
    {"x-db-host" (.getHost uri)
     "x-db-last-update" (quot (System/currentTimeMillis) 1000)
     "x-db-password" password
     "x-db-port" port
     "x-db-user" user}))

(defn- connection-details [tenant-conn]
  (let [db-uri (java.net.URI. (subs (-> tenant-conn :datasource .getJdbcUrl) 5))
        db-name (subs (.getPath db-uri) 1)]
    {:db-name db-name
     :headers (headers db-uri)}))

(defn do-create [tenant-conn windshaft-url dataset-id layer]
  (let [{:keys [table-name columns]} (dataset-by-id tenant-conn {:id dataset-id})
        where-clause (filter/sql-str columns (get layer "filters"))
        metadata (map-metadata/build tenant-conn table-name layer where-clause)
        {:keys [db-name headers]} (connection-details tenant-conn)
        url (format "%s/%s/layergroup" windshaft-url db-name)
        map-config (map-config/build table-name layer where-clause metadata)
        layer-group-id (-> (client/post url {:body (json/encode map-config)
                                             :headers headers
                                             :content-type :json})
                           :body json/decode (get "layergroupid"))]
    (lib/ok {"layerGroupId" layer-group-id
             "metadata" metadata
             "tenantDB" db-name})))

(defn create
  [tenant-conn windshaft-url dataset-id layer]
  (if (nil? dataset-id)
    (lib/bad-request {"reason" "No datasetID"})
    (do-create tenant-conn windshaft-url dataset-id layer)))



(comment
  ;; Example map spec
  {"type" "visualisation",
   "name" "Untitled visualisation",<commit_msg>[#1077] Validate layer spec WIP<commit_after>(ns akvo.lumen.lib.visualisation.maps
  (:require [akvo.lumen.lib :as lib]
            [akvo.lumen.lib.aggregation.filter :as filter]
            [akvo.lumen.lib.visualisation.map-config :as map-config]
            [akvo.lumen.lib.visualisation.map-metadata :as map-metadata]
            [akvo.lumen.util :as util]
            [cheshire.core :as json]
            [clj-http.client :as client]
            [hugsql.core :as hugsql]))

(hugsql/def-db-fns "akvo/lumen/lib/dataset.sql")

(defn- headers [uri]
  (let [{:keys [password user]} (util/query-map (.getQuery uri))
        port (let [p (.getPort uri)]
               (if (pos? p) p 5432))]
    {"x-db-host" (.getHost uri)
     "x-db-last-update" (quot (System/currentTimeMillis) 1000)
     "x-db-password" password
     "x-db-port" port
     "x-db-user" user}))

(defn- connection-details [tenant-conn]
  (let [db-uri (java.net.URI. (subs (-> tenant-conn :datasource .getJdbcUrl) 5))
        db-name (subs (.getPath db-uri) 1)]
    {:db-name db-name
     :headers (headers db-uri)}))

(defn do-create [tenant-conn windshaft-url dataset-id layer]
  (let [{:keys [table-name columns]} (dataset-by-id tenant-conn {:id dataset-id})
        where-clause (filter/sql-str columns (get layer "filters"))
        metadata (map-metadata/build tenant-conn table-name layer where-clause)
        {:keys [db-name headers]} (connection-details tenant-conn)
        url (format "%s/%s/layergroup" windshaft-url db-name)
        map-config (map-config/build table-name layer where-clause metadata)
        layer-group-id (-> (client/post url {:body (json/encode map-config)
                                             :headers headers
                                             :content-type :json})
                           :body json/decode (get "layergroupid"))]
    (lib/ok {"layerGroupId" layer-group-id
             "metadata" metadata
             "tenantDB" db-name})))

(defn invalid-location-spec? [layer]
  false)

(defn conform-create-args [dataset-id layer]
  (clojure.pprint/pprint layer)
  (cond
    (nil? dataset-id)
    (throw (ex-info "No datasetID"
                    {"reason" "No datasetID"}))
    (nil? layer)
    (throw (ex-info "No layer"
                    {"reason" "No layer"}))
    (invalid-location-spec? layer)
    (throw (ex-info "No geom"
                    {"reason" "No geom"}))
    :else [dataset-id layer]))


(defn create
  [tenant-conn windshaft-url dataset-id layer]
  (try
    (let [[dataset-id layer] (conform-create-args dataset-id layer)]
      (do-create tenant-conn windshaft-url dataset-id layer))
    (catch Exception e
      (lib/bad-request (ex-data e)))))




(comment
  ;; Example map spec
  {"type" "visualisation",
   "name" "Untitled visualisation",
{'fraction_non_alphanumeric': 0.1480524642289348, 'fraction_numerical': 0.0047694753577106515, 'mean_word_length': 2.2981651376146788, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3826797', 'n_tokens_mistral': 1699, 'n_tokens_neox': 1650, 'n_words': 396}