;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS INC Sucursal en España SL

(ns app.main.ui.workspace.tokens.management.forms.font-family
  (:require
   [app.common.files.tokens :as cfo]
   [app.common.schema :as sm]
   [app.common.types.token :as cto]
   [app.main.data.workspace.tokens.errors :as wte]
   [app.main.ui.workspace.tokens.management.forms.controls :as token.controls]
   [app.main.ui.workspace.tokens.management.forms.generic-form :as generic]
   [app.main.ui.workspace.tokens.management.forms.validators :refer [check-coll-self-reference default-validate-token]]
   [rumext.v2 :as mf]))

(defn- check-font-family-token-self-reference [token]
  (check-coll-self-reference (:name token) (:value token)))

(defn- validate-font-family-token
  [props]
  (-> props
      (update :token-value cto/split-font-family)
      (assoc :validators [(fn [token]
                            (when (empty? (:value token))
                              (wte/get-error-code :error.token/empty-input)))
                          check-font-family-token-self-reference])
      (default-validate-token)))

(mf/defc form*
  [{:keys [token token-type current-token-path] :rest props}]
  (let [token
        (mf/with-memo [token]
          (if token
            (update token :value cto/join-font-family)
            {:type token-type}))
        props (mf/spread-props props {:token token
                                      :token-type token-type
                                      :make-schema #(-> (cfo/make-token-schema %1 token-type current-token-path)
                                                        (sm/dissoc-key :id)
                                                        ;; The value as edited in the form is a simple stirng.
                                                        ;; It's converted to vector in the validator.
                                                        (sm/assoc-key :value cfo/schema:token-value-generic))
                                      :validator validate-font-family-token
                                      :input-component token.controls/fonts-combobox*})]
    [:> generic/form* props]))
