(ns com.oly.static-sites.do-blog.pages.helpers.database
  (:require [clojure.string :as str]
            [reagent.core :as r]
            [datascript.core :as d]
            [com.oly.static-sites.do-blog.pages.helpers.utils :refer [ltrim-slash]]))

(defonce schema {:tags {:db/cardinality :db.cardinality/many}})
(defonce conn (d/create-conn schema))
(defonce document (r/atom {}))
(defonce state
  (r/atom {:index []
           :refresh 1
           :search {:terms ""
                    :results []}
           :document {:details nil :body nil}
           :latest nil
           :current-doc ""
           :new-data 0
           :current-key :org-01}))

;(def not-empty? (complement empty?))

(def db-search
  '{:find [(pull ?e [*])]
    :in [$]
    :where
    [[?e :title ?title]
     [(get-else $ ?e :description :nil) ?description]
     [?e :date ?date]
     [(get-else $ ?e :thumbnail :nil) ?thumbnail]
     [?e :relative-path ?path]]})

(defn check-match [re-patt title]
  (re-find re-patt title))

(defn db-search-filter
  "Add where clauses to the datalog query when supplied"
  [{:keys [search tag]}]
  (let [re-search (if (not (str/blank? search)) #_(js/RegEx (str "(?i)" search))
                      (re-pattern (str "(?i)" search)) nil)]
    (cond-> db-search
      (not (str/blank? tag))
      (update-in  [:where] #(conj % ['?e :tags tag]))
      re-search
      (update-in  [:where] #(conj % [`(~'re-find ~re-search ~'?title)])))))

(defn search-articles [search]
  (->>
   (d/q (db-search-filter search) @conn)
   (flatten)
   (sort-by :date)
   reverse
   (map #(assoc %1 :relative-path (ltrim-slash (:relative-path %1))))))

(defn latest-article
  "Just return the first item from search articles."
  []
  (->> (search-articles {:search ""})
       first
       :relative-path))


