(ns auto-ap.ssr.company-dropdown
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.graphql.utils :refer [assert-can-see-client can-see-client?]]
   [auto-ap.ssr-routes :as ssr-routes]
   [auto-ap.ssr.components.navbar-dropdown :refer [navbar-dropdown]]
   [auto-ap.ssr.utils :refer [html-response]]
   [bidi.bidi :as bidi]
   [datomic.client.api :as dc]
   [hiccup2.core :as hiccup]))

(defn dropdown-contents [{:keys [identity]}]
  (let [options (->> (dc/q '[:find ?c ?n
                            :in $ ?user
                            :where [?c :client/name ?n]
                            [(auto-ap.graphql.utils/can-see-client? ?user ?c)]]
                          (dc/db conn)
                          identity)
                     (map (fn [[k v]]
                            {"key"   k
                             "value" v})))]
    (html-response 
      [:div.navbar-dropdown {:style {:width "20em"}}
       [:a.navbar-item {:hx-put       (bidi/path-for ssr-routes/only-routes
                                                       :active-client
                                                       :request-method :put)
                          :hx-target    "#company-dropdown"
                          :hx-swap      "outerHTML"
                          :hx-trigger   "click"}
        "All"]
       [:hr.navbar-divider]
       [:input#company-search.input.navbar-item {:placeholder "Company name"
                                                 :name        "search-text"
                                                 :autoFocus   true} ]
       [:input#company-search-value {:type       "hidden"
                                     :autocomplete "off"
                                     :name       "search-client"
                                     :hx-put     (bidi/path-for ssr-routes/only-routes
                                                                :active-client
                                                                :request-method :put)
                                     :hx-target  "#company-dropdown"
                                     :hx-swap    "outerHTML"
                                     :hx-trigger "change"} ]
       [:script
        (hiccup/raw
          (str "
var z = new autoComplete({
  selector:\"#company-search\",
  placeholder: \"Company Name....\",
  data: {
    keys: [\"value\"],
    src: " (cheshire.core/encode
             options)

               "
  },
  resultItem: {
    highlight:true,
    class: \"autocomplete-suggestion\",
    selected: \"highlighted\"

  },
  resultsList: {
    tabSelect: true
  },
  submit: true

});
z.input.addEventListener(\"selection\", function (event) {
  z.input.blur();
  z.input.value = event.detail.selection.value.value;
document.getElementById(\"company-search-value\").value= event.detail.selection.value.key;
document.getElementById(\"company-search-value\").dispatchEvent(new Event('change'));

});
"))]])))

(defn dropdown [request]

  (let [client (get-in request [:session :client])]

    (navbar-dropdown
      "company-dropdown"
      [:span 
       (if client
         (str "Company: " (:client/name client))
         "Company")
       [:script
        (hiccup/raw
          "localStorage.setItem(\"last-client-id\", \""(:db/id client)"\")")]]
      [:div {:hx-get 
             (bidi/path-for ssr-routes/only-routes
                            :company-dropdown-contents)
             :hx-swap   "outerHTML"
             :hx-trigger "intersect delay:150ms"
             :hx-target "closest .navbar-dropdown"
             :style {:width "20em"
                     :height "80px"}
             }
       [:div.loader.is-loading.is-active.is-centered]])))

(defn active-client [{:keys [identity params] :as request}]
  (let [client-id (some-> (or (:search-client params) (get params "search-client")) not-empty Long/parseLong)]
    (when client-id
      (assert-can-see-client identity client-id))
    (let [new-session (assoc (:session request) :client
                             (when client-id
                               (dc/pull (dc/db conn) [:db/id :client/name :client/code] client-id)))]
      (assoc 
        (html-response 
          (dropdown (assoc request :session new-session)))
        :session
        new-session
        :headers
        {"hx-trigger" "clientSelected"}))))
