(ns wanijo.schema.forms
  (:require [wanijo.attribute.db :as db-attr]
            [wanijo.attribute.domain :as domain-attr]
            [wanijo.schema.domain :as domain-schema]
            [clojure.string :refer [capitalize]]
            [clojure.spec.alpha :as spec]))

(defn unique-attr-name-in-schema! [req]
  (let [attr-uuid (get-in req [:params :uuid])
        name (get-in req [:params :name])
        schema-uuid (get-in req [:params :schema])
        matching-attr (db-attr/with-name-in-schema! name schema-uuid)]
    (or (nil? matching-attr)
        (= attr-uuid (:uuid matching-attr)))))

(spec/def ::unique-attr-name-per-schema
  unique-attr-name-in-schema!)

(def schema
  {:fields {:name {:label "Name"
                   :required true
                   :spec ::domain-schema/name}
            :uuid {:widget :hidden}}})

(def attr-form
  {:fields {:name {:label "Name"
                   :required true
                   :spec ::domain-attr/name}
            :type {:label "Type"
                   :required true
                   :spec ::domain-attr/type
                   :widget :select
                   :options (map #(vector (capitalize %) %)
                                 domain-attr/types)}
            :required {:label "Required"
                       :required false
                       :widget :checkbox
                       :from-req #(if (some? %) 1 0)}
            :uuid {:widget :hidden}}
   :form-specs [::unique-attr-name-per-schema]})

(def assign-form
  {:fields {:assigned {:label "Users"
                       :required false
                       :spec :wanijo.schema.domain/assigned-to
                       :widget :mselect
                       :from-req #(if (vector? %) % [%])}
            :uuid {:widget :hidden}}})

(def schema-connections-form
  {:fields {:connections {:label "Schemas"
                          :required false
                          :spec :wanijo.schema.domain/assigned-to
                          :widget :mselect
                          :from-req #(if (vector? %) % [%])}
            :uuid {:widget :hidden}}})
