             [neko.threading :refer [on-ui]]
             [neko.log :as log]
             [neko.intent :as intent]
+            [neko.notify :refer [toast]]
             [neko.ui :refer [make-ui]]
             [neko.ui.mapping :refer [defelement]]
             [uk.org.potentialdifference.darknet.config :refer [config]]

                   :camera parse-long})))

(defn replace-view! [^Activity this ^View new]
  (on-ui
      (when-let [^View container (find-view this ::container)]
        (let [^View old (.getChildAt  container 0)]
          (.removeView container old)
          (.addView container new 0)))))

(defn create-mjpeg-view ^MjpegView [^Context context source-url width height]
  (let [^MjpegView mjpeg-view (new MjpegView context)]

                 (make-ui activity
                          [:text-view {:text "Waiting..."}])))

(defn setVideoSource [video source]
  (log/i "darknet setting video source" source)
  (if (.startsWith source "http")
    (.setVideoUri video (Uri/parse source))
    (.setVideoPath video source)))

(defn setup-video-view [view activity path]
  (doto view
    (fit-linear-layout!)
    (setVideoSource path)
    (.setOnCompletionListener (reify
                                MediaPlayer$OnCompletionListener
                                (onCompletion [this mp]
                                  (default-view activity))))
    (.start))
  view)

(defn video-from-path [activity path]
  (setup-video-view (VideoView. activity) activity path))

(defn save-local! [activity instruction]
  (when-let [name (:name instruction)]
    (when-let [url (:url instruction)]
      (server/get-bytes url
                        (fn [bytes]
                          (storage/write-bytes! bytes name))))))

(defn layout [activity view]
  (make-ui activity
           [:linear-layout {:background-color Color/BLACK
                            :gravity Gravity/CENTER}
            view]))

(defn view-local [activity instruction]
  (when-let [name (:name instruction)]
    (when-let [path (storage/local-path name)]
      (case (:type instruction)
        "image" (layout activity (image-from-path activity path))
        "video" (layout activity (video-from-path activity path))))))

(defn swap-view! [activity view]
  (replace-view! activity view))

(defactivity uk.org.potentialdifference.darknet.MainActivity
  :key :main
