(ns auto-ap.views.components.number
  (:require [react :as react]
            [reagent.core :as r]))


(defn number-internal [props]
  
  (let [[text set-text ]   (react/useState (some-> props :value str))
        [value set-value ] (react/useState (some-> props :value))
        coerce-value (fn [new-value]
                       (let [new-value (js/parseInt new-value)]
                         (cond
                           (nil? new-value)
                           nil

                           (js/Number.isNaN new-value)
                           nil

                           :else
                           new-value)))]
    (react/useEffect (fn []
                       (let [prop-value (:value props)]
                         (when (not (= prop-value value))
                           (set-value prop-value)
                           (if prop-value 
                             (set-text (str prop-value))
                             (set-text ""))))))
    [:div.field.has-addons 
     [:div.control 
      [:input.input (assoc props
                           :on-change (fn [e]
                                        ((:on-change props)
                                         (coerce-value (.. e -target -value))))
                           :value text
                           :type  "number"
                           :step  "1"
                           :style (or (:style props)
                                      {:width "5em"})
                           :size  3)]]]))

(defn number-input []
  [:f> number-internal
   (r/props (r/current-component))])

