 (ns tropefest.api
-  (:require [tropefest.db :as db]))
+  (:require [tropefest.db :as db]
+            [com.numergent.url-tools :as ut]))
 
 
 (defn node-size [rel-count]

(defn network-from-node
  [code]
  (let [conn       (db/get-connection)
        node       (:data (db/query-by-id conn code))
        links-from (db/query-from conn code :LINKSTO)
        links-to   (db/query-to conn :LINKSTO code)
        links-set  (set (concat links-from links-to))]
    {:nodes (concat
              [(transform-node node 0 0)]
              (map #(transform-node %1 (rand-range 50) (rand-range 50)) links-set)
              ; (map-indexed #(transform-node %2 %1 1) links-from)
              ; (map-indexed #(transform-node %2 %1 2) links-to)
              )
     :edges (edge-collection node links-from links-to)})
  )
        (assoc "x" x "y" y "size" (node-size (stringed "incoming")) "label" (stringed "id")))))

(defn edge
  "Returns an edge map. Does not return an index, since those are disposable
  and can be assigned later."
  [from to color]
  {:source from
   :target to
   :color  color
   :type   "arrow"})                                        ; Could be line, curve, arrow or curvedArrow

(defn edge-collection
  [{node       :node
    links-from :links-from
    links-to   :links-to
    color-from :color-from
    color-to   :color-to}]
  (let [edges-from (map #(edge (node "id") (%1 "id") (ut/if-nil color-from "#ff3300")) links-from)
        edges-to   (map #(edge (%1 "id") (node "id") (ut/if-nil color-to "#0066ff")) links-to)]
    (concat edges-from edges-to)))

(defn query-related-from
  [conn code-from node]
  {:node       node
   :links-from (db/query-common-nodes-from conn code-from (node "id"))})

(defn rand-range [n]
  (- (rand n) (/ n 2)))
