(defn fetch-media-buffer [ctx url cb-fn]
  (let [promise (js/call (js/global "window") "fetch" url)]
    (js/call promise "then" (fn [r]
      (js/call (js/call r "arrayBuffer") "then" (fn [buf]
        (js/call (js/call ctx "decodeAudioData" buf) "then" (fn [audio-buf]
          (cb-fn audio-buf)))))))))

(defn load-local-audio-file [ctx cb-fn]
  (let [document (js/global "document")
        input (js/call document "createElement" "input")]
    (js/set input "type" "file")
    (js/set input "accept" "audio/*")
    (js/set input "onchange" (fn [e]
      (let [target (js/get e "target")
            files (js/get target "files")
            file (if files (js/get files "0") nil)]
        (if file
          (let [reader (js/new (js/global "FileReader"))]
            (js/set reader "onload" (fn [ev]
              (let [ev-target (js/get ev "target")
                    result (js/get ev-target "result")
                    promise (js/call ctx "decodeAudioData" result)]
                (js/call (js/call promise "then" (fn [audio-buf]
                           (let [fname (js/get file "name")
                                 fpath (js/get file "path")
                                 label (if fpath fpath fname)]
                             (cb-fn audio-buf label))))
                         "catch" (fn [err] (js/log "Decode error"))) nil)))
            (js/call reader "readAsArrayBuffer" file)) nil))))
    (js/call input "click")))

(defn load-remote-audio-file [ctx path cb-fn]
  (let [window (js/global "window")
        promise (js/call window "fetch" path)]
    (js/call promise "then"
      (fn [res]
        (if (js/get res "ok")
          (let [arr-prom (js/call res "arrayBuffer")]
            (js/call arr-prom "then"
              (fn [array-buf]
                (if array-buf
                  (let [decode-prom (js/call ctx "decodeAudioData" array-buf)]
                    (js/call decode-prom "then"
                      (fn [audio-buf]
                        (cb-fn audio-buf path))
                      (fn [err]
                        (js/log (str "Decode error: " path)))) nil)
                  nil))))
          (js/log (str "Failed to fetch HTTP Audio Asset: " path)))))
    nil))