 (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]]


(def ssl? (= (.getScheme uri) "https"))

(def app-state (atom {:bookmarks []}))


;; fire up repl
#_(do
    (ns weasel.startup)
    (require 'weasel.repl.websocket)
    (cemerick.piggieback/cljs-repl
        :repl-env (weasel.repl.websocket/repl-env
                   :ip "0.0.0.0" :port 9001)))


;; weasel websocket, development only
#_(if (= "localhost" (.getDomain uri))
  (do
    #_(ws-repl/connect "ws://localhost:9001" :verbose true)
    (figw/watch-and-reload
     :jsload-callback (fn [] (print "reloaded")))))



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


(defn send-registry
  "Send mail for sign up"
  [app owner]
  (let [email (om/get-state owner :signup-text)
        [in _] (-> app deref :ws)]
    (if (clojure.string/blank? email)
      (println "INFO: no mail")
      (do
        (go (>! in {:topic :sign-up :data {:email email}}))
        (om/transact! app :user (fn [old] email))
        (om/set-state! owner :signup-text "")))))


;; --- NAVBAR ---

(deftemplate nav "templates/navbar.html"
  [app owner state]
  {[:#brand] (content "Lesezeichen")
   [:#sign-up-input] (do-> (set-attr :value (:signup-text state))
                           (listen :on-change #(handle-text-change % owner :signup-text)
                                   :on-key-down #(if (= (.-keyCode %) 10)
                                                   (send-registry app owner)
                                                   (when (= (.-which %) 13)
                                                     (when (.-ctrlKey %)
                                                       (send-registry app owner))))))
   [:#modal-signup-btn] (listen :on-click (fn [e] (send-registry app owner)))})


;; --- MAIN VIEW ---
