 (defn parse-message
   "Parse a Portal message."
   [message]
-  (let [message (second (.split (apply str (butlast (str message)))":"))
-        [id type content] (.split message " ")]
+  (let [message (second (split (string/join (butlast (str message))) #":" 2))
+        [id type content] (split message #" " 3)]
+    (prn "message:" message)
     {:type (keyword type)
      :id id
-     :content content}))
+     :content (string/join " " content)}))
 
 (defn send-message
   "Send a portal message."


(defn eval
  "Evaluate code."
  ([sock form] (eval sock form (rand-int 9999999999999999)))
  ([sock form id & [callback]]
     (send-message sock id "eval" form)))

(defn tail
  "Tail stdout or stderr from a context."

    (cond (#{:stdout :stderr} type)
          (update-context id type conj content)
          (#{:result :error :read-error} type)
          (let [count (update-context id :result inc)]
            #_(prn @contexts)
            ((get-in (context id) [:callbacks count])
             (let [vals (butlast (.split content "\n"))]
               (if (= type :result)
                 vals
                 (conj (butlast vals) {type (last vals)}))))))
    #_(prn data)))

(defn connect
  ([port] (connect port "localhost"))
  ([port host]
     (doto (.createConnection net port host)
       (.on "data" on-data))))

(defn test-fn [data]
  (prn "result" data))

(defn -main [& args]
  (let [sock (connect 1337 "localhost")]
    (eval sock "(+ 1 2 3 4 5)" test-fn)
    (eval sock "(slurp \"http://lazybot.org\")" test-fn)))

(set! *main-cli-fn* -main)