 (ns lesezeichen.core
   (:require [figwheel.client :as figw :include-macros true]
-            [weasel.repl :as ws-repl]
             [cljs.core.async :refer [put! chan <! >! alts! timeout close!] :as async]
             [cljs.reader :refer [read-string] :as read]
             [kioo.om :refer [content set-attr do-> substitute listen]]


(defn send-bookmark
  "Send bookmark via websocket to server"
  [state owner]
  (let [url (om/get-state owner :url-input-text)
        ws-in (om/get-state owner :ws-in)]
    (if (clojure.string/blank? url)
      (println "INFO: no input")
      (do
        (go (>! ws-in {:topic :add-bookmark :data {:email "eve@topiq.es" :url url}}))
        (om/set-state! owner :url-input-text "")))))

;; --- NAVBAR ---

(deftemplate nav "templates/navbar.html"
  [app owner]
  {[:#brand] (content "Lesezeichen")})


;; --- MAIN VIEW ---

   [:#url-input] (do-> (set-attr :value (:url-input-text state))
                       (listen :on-change #(handle-text-change % owner :url-input-text)
                               :on-key-down #(if (= (.-keyCode %) 10)
                                               (send-bookmark app owner)
                                               (when (= (.-which %) 13)
                                                 (when (.-ctrlKey %)
                                                   (send-bookmark app owner))))))
   [:#search-input] (do-> (set-attr :value (:search-text state))
                          (listen :on-change #(handle-text-change % owner :search-text)))
   [:#url-list] (content (let [bms (if (blank? (:search-text state))
                                     (:bookmarks app)
                                     (remove
                                      (fn [bookmark]
                                        (nil?
                                         (re-find
                                          (-> state :search-text trim lower-case re-pattern)
                                          (-> bookmark :title lower-case))))
                                      (:bookmarks app)))]
                           (map #(url %) (sort-by :ts > bms))))
   [:#bookmark-btn] (listen :on-click (fn [e] (send-bookmark app owner)))})


;; --- VIEWS ---
(defn nav-view
  "Navbar view handling sin-up and log-in menu"
  [app owner]
  (reify
    om/IInitState
    (init-state [_]
      {:signup-text ""})
    om/IWillMount
    (will-mount [_]
      (go
