 (ns mininova-web-ui.ui
-  (:require [reagent.core :as reagent]
+  (:require [reagent.core :as r]
             [re-frame.core :as rf]
             [mininova-web-ui.midi :as midi]
             [mininova-web-ui.params :as params]))
 
+(def patch-inspector-enabled? true)
+
 (def patch-request-message
   [0xF0 0x00 0x20 0x29 0x03 0x01 0x7F 0x40 0x00 0x00 0x00 0x00 0x00 0xF7])
 
 (def patch-response-sentinel
   [0xF0 0x00 0x20 0x29 0x03 0x01 0x7F 0x00 0x00 0x09 0x04])
 
-(def default-panel :osc)
+(def default-panel (keyword (subs js/location.hash 1)))
 
 ;; FIXME: Get ridi of `re-frame: no :fx handler registered for :event` error
 (rf/reg-fx :event (fn [_ _]))

      [:li [toggle {:id :arp-7/step :label "Step 7"}]]
      [:li [toggle {:id :arp-8/step :label "Step 8"}]]]])

(defn main-panel []
  (let [tab @(rf/subscribe [::panel])]
    [:main.main-panel


(defn make-set-patch-value [data]
  (fn [db [id param]]
    (if (and (contains? param :offset) (not= 0 (:offset param)))
      (assoc-in db [::control id] (nth data (:offset param)))
      db)))

(defn apply-patch [db data]
  (reduce (make-set-patch-value data) db params/params))

(rf/reg-event-db ::midi/sysex
  [rf/debug]
  (fn [db [_ data]]
    (if (patch-dump? data)
      (-> db
          (apply-patch data)
          (assoc ::patch data)))))

(rf/reg-sub ::patch
  (fn [db]
    (::patch db)))

(defn tab [{:keys [id]}]
  (let [current-tab @(rf/subscribe [::panel])]
    [:a {:class (if (or (= current-tab id)) (nil? current-tab) "is-active")
         :href (str "#" (name id))
         :on-click #(rf/dispatch [::panel id])}
      (first (r/children (r/current-component)))]))

(defn tabs []
  [:ul.tabs
    [:li [tab {:id :filter} "Filter"]]
    [:li [tab {:id :env} "Env"]]
    [:li [tab {:id :lfo} "LFO"]]
    [:li [tab {:id :arp} "ARP"]]
    (if patch-inspector-enabled?
      [:li [tab {:id :patch-inspector} "Patch inspector"]])])

(defn map-in-out [in out value]
  (+ (- value (first in)) (first out)))
