(require "libs/reframe/src/reframe_wasm.coni")
(require "libs/math/src/math.coni" :as math)

(js/set (js/global "globalThis") "make_float32_array" (fn [len] (js/new (js/global "Float32Array") len)))
(defn make-float32-array [len] (js/call (js/global "globalThis") "make_float32_array" len))

(defn f32-set! [arr idx val]
  (js/set arr (str idx) val))

(println "[DSP Worker] Thread Initialized. Awaiting Reverb/Distortion DSP Generation Queries...")

(js/on-event (js/global "globalThis") :message
  (fn [evt]
    (let [data (js/get evt "data")
          msg-type (nth data 0)
          payload (nth data 1)]
      (cond
        (= msg-type :calc-reverb)
        (let [n-id (:id payload)
              sr (:sampleRate payload)
              duration (:duration payload)
              decay (:decay payload)
              len (int (* sr duration))
              ch1 (make-float32-array len)
              ch2 (make-float32-array len)]
          (loop [j 0]
            (if (< j len)
              (do
                (f32-set! ch1 j (* (- (* (math/random) 2.0) 1.0) (math/pow (- 1.0 (/ j len)) decay)))
                (f32-set! ch2 j (* (- (* (math/random) 2.0) 1.0) (math/pow (- 1.0 (/ j len)) decay)))
                (recur (+ j 1)))
              nil))
          (js/call (js/global "globalThis") "postMessage" 
            [:reverb-done {:id n-id :ch1 ch1 :ch2 ch2 :len len}]))
            
        (= msg-type :calc-distortion)
        (let [n-id (:id payload)
              amount (:amount payload)
              k (if amount amount 50.0)
              n-samples 44100
              curve (make-float32-array n-samples)
              deg (/ math/PI 180.0)]
          (loop [i 0]
            (if (< i n-samples)
              (let [x (- (* (/ (* i 2.0) n-samples)) 1.0)]
                (f32-set! curve i (/ (* (* (* (+ 3.0 k) x) 20.0) deg) (+ math/PI (* k (math/abs x)))))
                (recur (+ i 1)))
              nil))
          (js/call (js/global "globalThis") "postMessage" 
            [:distortion-done {:id n-id :curve curve}]))
            
        :else nil))))

(<! (chan 1))
