(ns com.oly.static-sites.clojure-demos.helpers
  (:require
   [cljs.core.async :refer [go]]
   [cljs.core.async.interop :refer [<p!]]
   [com.oly.static-sites.clojure-demos.state :refer [site-state]]
   [clojure.string :as str]))

(defn slugify [s]
  (when s
    (str
     (-> s
         (str/lower-case)
         (str/replace #"[^\w]+" "-")
         (str/replace #"^-\\|-\\-$" "")))))

(defn build-page-path [title]
  (str "http://127.0.0.1:8080/" #_"https://clojure-demos.digitaloctave.com/" "page/"
       (when (-> @site-state :current-route :parameters :path :page)
         (-> @site-state :current-route :parameters :path :page))
       "#" title))


(defn copy->clipboard
  "Simple wrapper which copies text to the clipboard and resolves the promise"
  [text]
  (go (<p! (.writeText (.-clipboard js/navigator) (build-page-path text))) 
      (swap! site-state assoc :notification "Copied to clipboard")
      (prn "copied")))

(defn map-replace
  "Given a string with {:key} strings substitute the matching key in a hash map"
  [text m]
  (reduce
   (fn [acc [k v]] (str/replace acc (str "{" k "}") (str v)))
   text m))


(comment
  (map-replace "/page/{page}" "page")
  (re-seq #"\{(.*?)\}" "/page/{page}/{id}" )
  (->> (re-seq #"\{(.*?)\}" "/page/{page}/{id}" )
       (map second))
  ;(re-seq #"{(.*?)}" "/page/{page}" )
  (re-seq #"\[(.*?)\]" "/page/[page]" )
  (.-writeText (.-clipboard js/navigator) "test")
  (copy->clipboard "test2"))
