(ns lineup.components.edit
  (:require
   [lineup.components.edit.selector :refer [task-selector]]
   [lineup.events :as events]
   [lineup.subs :as subs]
   [re-com.core :as re-com]
   [re-frame.core :as re-frame]))

(defn- task-editor [index task]
  [re-com/h-box
   :gap "20px"
   :class "task-editor"
   :padding "0 10px"
   :align :center
   :attr {:on-click #(re-frame/dispatch [::events/select-selecting index])}
   :children
   [[re-com/box
     :size "none"
     :child
     [re-com/title
      :label (inc index)
      :level :level1]]
    [re-com/box
     :width "100px"
     :height "100px"
     :max-width "100px"
     :max-height "100px"
     :justify :center
     :child
     [:img
      {:src (:image task)}]]
    [re-com/box
     :size "1"
     :child
     [re-com/title
      :label (:name task)
      :level :level3]]
    [re-com/box
     :size "none"
     :child
     ;TODO: add move up and move down buttons (row buttons)
     [re-com/button
      :label "X"
      :on-click #(do
                   (re-frame/dispatch [::events/remove-task index])
                   (.stopPropagation %))]]]])

(defn- schedule-editor []
  (let [schedule-data (re-frame/subscribe [::subs/schedule])
        library-data (re-frame/subscribe [::subs/library])
        library (fn [id]
                  (some #(when (= (:id %) id) %) @library-data))]
    ;TODO: convert to table (with row buttons)
    [re-com/v-box
     :gap "10px"
     :height "100%"
     :children
     (concat
      (map-indexed
       (fn [index task]
         ^{:key (str "edit-task-" index)}
         [task-editor index (library (:ref task))])
       (:tasks @schedule-data []))
      [[re-com/box
        :max-width "50%"
        :margin "0 0 0 20px"
        :child
        [re-com/button
         :label "+ add"
         :class "btn-primary btn-block"
         :on-click #(re-frame/dispatch [::events/select-selecting (count (:tasks @schedule-data))])]]])]))

(defn edit []
  (let [selecting (re-frame/subscribe [::subs/selecting])]
    [re-com/v-box
     :gap "10px"
     :height "100%"
     :children
     [[re-com/title
       :label "Schedule Editor"
       :level :level3]
      [schedule-editor]
      (when @selecting
        [task-selector @selecting])]]))
