 ;; Server message handling
 
 (defn handle-query-result [d]
-  (do
-    (log (apply str (map :competition/name d)))
-    ;(d/transact! (d/db conn) )
-    (d/transact! conn [{:db/id 1 :competition/name (apply str (map :competition/name d))}])
+  (let [clean-data (uidb/sanitize d)]
+     ;(log clean-data)   
+    ;(log (apply str (map :competition/name clean-data)))
+                                        ;(d/transact! (d/db conn) )
+    (d/transact! conn [clean-data])
+    (log (d/q '[:find [(pull ?c [:class/name]) ...]
+                :where
+                [?e :competition/name "Rikstävling disco"]
+                [?e :competition/classes ?c]]
+              (d/db conn)))
+    ;(d/transact! conn [{:db/id 1 :competition/name (apply str (map :competition/name clean-data))}])
     ))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

            [om.dom :as dom]
            [cljs.core.async :as async :refer (<! >! put! chan)]
            [taoensso.sente :as sente :refer (cb-success?)]
            [datascript.core :as d]))

(def test-data
  {:competition/name "TurboMegatävling",
   :competition/date #inst "2014-11-22T00:00:00.000-00:00",
   :competition/location "THUNDERDOME",
   :competition/options
   {:dance-competition/same-heat-all-dances true,
    :presentation/chinese-fonts true,
    :dance-competition/heat-text-on-adjudicator-sheet true,
    :dance-competition/name-on-number-sign true,
    :dance-competition/skip-adjudicator-letter true,
    :presentation/courier-font "NSimSun",
    :dance-competition/adjudicator-order-final true,
    :dance-competition/random-order-in-heats true,
    :dance-competition/club-on-number-sign true,
    :dance-competition/adjudicator-order-other true,
    :presentation/arial-font "SimSun",
    :printer/preview true,
    :printer/printer-select-paper true}
   :competition/panels
   [{:adjudicator-panel/name "1",
     :adjudicator-panel/id 4,
     :adjudicator-panel/adjudicators
     [{:adjudicator/id 1,
       :adjudicator/name "Anders",
       :adjudicator/country "Sweden"}
      {:adjudicator/id 2,
       :adjudicator/name "Bertil",
       :adjudicator/country ""}]}
    {:adjudicator-panel/name "2",
     :adjudicator-panel/id 5,
     :adjudicator-panel/adjudicators
     [{:adjudicator/id 2,
       :adjudicator/name "Bertil",
       :adjudicator/country ""}
      {:adjudicator/id 3,
       :adjudicator/name "Cesar",
       :adjudicator/country ""}]}],
   :competition/adjudicators
   [{:adjudicator/id 1,
     :adjudicator/name "Anders",
     :adjudicator/country "Sweden"}
    {:adjudicator/id 2,
     :adjudicator/name "Bertil",
     :adjudicator/country ""}
    {:adjudicator/id 3,
     :adjudicator/name "Cesar",
     :adjudicator/country ""}],
   :competition/activities
   [{:activity/name "",
     :activity/number -1,
     :activity/comment "A comment",
     :activity/id 35,
     :activity/position 1,
     ;:activity/time nil,
     ;:activity/source nil
     }
    {:activity/name "Hiphop Singel Star B",
     :activity/number 1,
     :activity/comment "",
     :activity/id 37,
     :activity/position 2,
     :activity/time #inst "2014-11-22T10:00:00.000-00:00",
     :activity/source
     {:round/status :not-started,
      :round/panel
      {:adjudicator-panel/name "2",
       :adjudicator-panel/id 5,
       :adjudicator-panel/adjudicators
       [{:adjudicator/id 2,
         :adjudicator/name "Bertil",
         :adjudicator/country ""}
        {:adjudicator/id 3,
         :adjudicator/name "Cesar",
         :adjudicator/country ""}]},
      :round/class-id 41,
      :round/id 36,
      :round/dances [{:dance/name "Medium"}],
    :round/results
    [{:result/participant-number 30,
      :result/recalled "",
      :result/judgings
      ({:judging/adjudicator 1, :juding/marks [{:mark/x true}]}
       {:judging/adjudicator 2, :juding/marks [{:mark/x false}]}
       {:judging/adjudicator 3, :juding/marks [{:mark/x true}]})}
     {:result/participant-number 31,
      :result/recalled "",
      :result/judgings
      ({:judging/adjudicator 1, :juding/marks [{:mark/x false}]}
       {:judging/adjudicator 2, :juding/marks [{:mark/x true}]}
       {:judging/adjudicator 3, :juding/marks [{:mark/x false}]})}
     {:result/participant-number 32,
      :result/recalled "",
      :result/judgings
      ({:judging/adjudicator 1, :juding/marks [{:mark/x true}]}
       {:judging/adjudicator 2, :juding/marks [{:mark/x false}]}
       {:judging/adjudicator 3, :juding/marks [{:mark/x false}]})}],
    :round/index 0,
    :round/starting
    [{:participant/name "Rulle Trulle",
      :participant/club "Sinus",
      :participant/number 30,
      :participant/id 38}
     {:participant/name "Hush Bush",
      :participant/club "Zilson",
      :participant/number 31,
      :participant/id 39}
     {:participant/name "Banana Hamock",
      :participant/club "Zzzz",
      :participant/number 32,
      :participant/id 40}],
    :round/heats 2,
    :round/type :normal-x,
    :round/number 1,
    :round/start-time #inst "2014-11-22T10:00:00.000-00:00",
    :round/recall 6}}],
 :competition/classes
 ({:class/adjudicator-panel
   {:adjudicator-panel/name "1",
    :adjudicator-panel/id 4,
    :adjudicator-panel/adjudicators
    [{:adjudicator/id 1,
      :adjudicator/name "Anders",
      :adjudicator/country "Sweden"}
     {:adjudicator/id 2,
      :adjudicator/name "Bertil",
      :adjudicator/country ""}]},
   :class/starting
   [{:participant/name "Rulle Trulle",
     :participant/club "Sinus",
     :participant/number 30,
     :participant/id 38}
    {:participant/name "Hush Bush",
     :participant/club "Zilson",
     :participant/number 31,
     :participant/id 39}
    {:participant/name "Banana Hamock",
     :participant/club "Zzzz",
     :participant/number 32,
     :participant/id 40}],
   :class/dances
   [{:dance/name "Medium"}
    {:dance/name "Tango"}
    {:dance/name "VienWaltz"}],
   :class/remaining
   [{:participant/name "Rulle Trulle",
     :participant/club "Sinus",
     :participant/number 30,
     :participant/id 38}
    {:participant/name "Hush Bush",
     :participant/club "Zilson",
     :participant/number 31,
     :participant/id 39}
    {:participant/name "Banana Hamock",
     :participant/club "Zzzz",
     :participant/number 32,
     :participant/id 40}],
   :class/position 1,
   :class/name "Hiphop Singel Star B",
   :class/rounds
   [{:round/status :not-started,
     :round/panel
     {:adjudicator-panel/name "2",
      :adjudicator-panel/id 5,
      :adjudicator-panel/adjudicators
      [{:adjudicator/id 2,
        :adjudicator/name "Bertil",
        :adjudicator/country ""}
       {:adjudicator/id 3,
        :adjudicator/name "Cesar",
        :adjudicator/country ""}]},
     :round/class-id 41,
     :round/id 36,
     :round/dances [{:dance/name "Medium"}],
     :round/results
     [{:result/participant-number 30,
       :result/recalled "",
       :result/judgings
       ({:judging/adjudicator 1, :juding/marks [{:mark/x true}]}
        {:judging/adjudicator 2, :juding/marks [{:mark/x false}]}
        {:judging/adjudicator 3, :juding/marks [{:mark/x true}]})}
      {:result/participant-number 31,
       :result/recalled "",
       :result/judgings
       ({:judging/adjudicator 1, :juding/marks [{:mark/x false}]}
        {:judging/adjudicator 2, :juding/marks [{:mark/x true}]}
        {:judging/adjudicator 3, :juding/marks [{:mark/x false}]})}
      {:result/participant-number 32,
       :result/recalled "",
       :result/judgings
       ({:judging/adjudicator 1, :juding/marks [{:mark/x true}]}
        {:judging/adjudicator 2, :juding/marks [{:mark/x false}]}
        {:judging/adjudicator 3, :juding/marks [{:mark/x false}]})}],
     :round/index 0,
     :round/starting
     [{:participant/name "Rulle Trulle",
       :participant/club "Sinus",
       :participant/number 30,
       :participant/id 38}
      {:participant/name "Hush Bush",
       :participant/club "Zilson",
       :participant/number 31,
       :participant/id 39}
      {:participant/name "Banana Hamock",
       :participant/club "Zzzz",
       :participant/number 32,
       :participant/id 40}],
     :round/heats 2,
     :round/type :normal-x,
     :round/number 1,
     :round/start-time #inst "2014-11-22T10:00:00.000-00:00",
     :round/recall 6}],
   :class/id 41}
  {:class/adjudicator-panel nil,
   :class/starting
   [{:participant/name "Ringo Stingo",
     :participant/club "Kapangg",
     :participant/number 20,
     :participant/id 42}
    {:participant/name "Greve Turbo",
     :participant/club "OOoost",
     :participant/number 21,
     :participant/id 43}],
   :class/dances [],
   :class/remaining
   [{:participant/name "Ringo Stingo",
     :participant/club "Kapangg",
     :participant/number 20,
     :participant/id 42}
    {:participant/name "Greve Turbo",
     :participant/club "OOoost",
     :participant/number 21,
     :participant/id 43}],
   :class/position 2,
   :class/name "Hiphop Singel Star J Fl",
   :class/rounds [],
   :class/id 44})})

;https://github.com/omcljs/om/wiki/Quick-Start-%28om.next%29

(enable-console-print!)

;; (def output-el (.getElementById js/document "output"))

;; (defn ->output! [fmt & args]
;;   (let [msg (apply encore/format fmt args)]
;;     (timbre/debug msg)
;;     (aset output-el "value" (str "• " (.-value output-el) "\n" msg))
;;     (aset output-el "scrollTop" (.-scrollHeight output-el))))

(defn log [m]
  (.log js/console m))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Init DB


(def conn (d/create-conn {:competition/classes {:db/cardinality :db.cardinality/many
                                                :db/valueType :db.type/ref}
                          :competition/options {:db/isComponent true
                                                :db/valueType :db.type/ref}

                          :competition/panels {:db/cardinality :db.cardinality/many
                                                :db/valueType :db.type/ref}

                          :adjudicator-panel/adjudicators {:db/cardinality :db.cardinality/many
                                                           :db/valueType :db.type/ref}

                          :competition/activities {:db/cardinality :db.cardinality/many
                                                   :db/valueType :db.type/ref}

                          :activity/source {:db/cardinality :db.cardinality/one
                                            :db/valueType :db.type/ref}

                          :round/dances  {:db/cardinality :db.cardinality/many
                                                   :db/valueType :db.type/ref}

                          ;:class/name {:db/unique :db.unique/identity}
                          }))

;; Test of transacting 'flat'
;; (d/transact! conn [{:db/id 1 :competition/name "A"}
;;                    {:db/id 1 :competition/classes 2}
;;                    {:db/id 1 :competition/classes 3}
;;                    {:db/id 2 :class/name "Disco"}
;;                    {:db/id 3 :class/name "Tango"}])

;; Test of transacting list of e/id
;; (d/transact! conn [{:db/id 1 :competition/name "A"}
;;                    {:db/id 1 :competition/classes [2 3]}
;;                    {:db/id 2 :class/name "Disco"}
;;                    {:db/id 3 :class/name "Tango"}])

;; Test of transaction with nested creation
;; (d/transact! conn [{:db/id -1 :competition/name "A"}
;;                    {:db/id -1 :competition/classes
;;                     [{:db/id -2 :class/name "Disco"}
;;                      {:db/id -3 :class/name "Tango"}]}

;;                    {:db/id -1 :competition/location "Vås"}

;;                    {:db/id -1 :competition/options
;;                     {:option/is-good true}}

;;                    {:db/id -4 :competition/name "B" :competition/location "Ups"}
;;                    ])

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Test with Small Example

(declare test-data)

(log (select-keys test-data [:competition/name]))
;(d/transact! conn [(select-keys test-data [:competition/name :competition/options])])

;; TODO - competition/adjudicators och panels, must fix ID ref, and round panel
;; TODO - do all nil values need to be filtered?
(def tx-data
  (let [tx (select-keys test-data [:competition/name :competition/activities])]
    (:activity/source (second (:competition/activities tx)))))

(log tx-data)

(d/transact! conn [tx-data])

;[(pull ?e ?selector) ...]
;; (log
;;  (d/q '[:find [(pull ?c [:class/name]) ...] 
;;         :where
;;         [?e :competition/name "A"]
;;         [?e :competition/classes ?c]]
;;       (d/db conn)))

 (log (pr-str (d/db conn)))
;; (d/transact! conn
;;   [{:db/id -1
;;     :app/title "Hello, DataScript!"
;;     :app/count 0}])

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Sente Socket setup

      (log (str "Sent to Tango Backend => " remote))
      (chsk-send! [:event-manager/query [[:competition/name :competition/location]]]))))

;; TODO - since conn is set the read query will be run twice at start up - delay read or something.. 
(def reconciler
  (om/reconciler
    {:state conn
