(ns wanijo.attribute.routes
  (:require [compojure.core :refer [defroutes GET POST DELETE] :as comp]
            [clojure.pprint :refer [pprint]]
            [ring.util.response :as resp]
            [formulare.core :as form]
            [wanijo.infrastructure.routing :refer [register! path]]
            [wanijo.attribute.db :as domain]
            [wanijo.schema
             [routes :as schema-routes]
             [forms :as schema-forms]
             [middleware :as schema-middleware]]))

(defn new! [req]
  (let [schema-uuid (get-in req [:params :schema])]
    (if (form/valid? schema-forms/attr-form req)
      (do
        (domain/create-new! (form/form-data schema-forms/attr-form
                                            req)
                            schema-uuid
                            (get-in req [:session :uuid]))
        (resp/redirect (path :schema-show {:uuid schema-uuid})))
      (schema-routes/view! schema-uuid req))))

(defn edit! [schema-uuid req]
  (if (form/valid? schema-forms/attr-form req)
    (do
      (domain/edit! (form/form-data schema-forms/attr-form req))
      (resp/redirect (path :schema-show {:uuid schema-uuid})))
    (schema-routes/view! schema-uuid req)))

(defn delete! [uuid req]
  (domain/delete-by-uuid! uuid)
  (resp/redirect (path :schema-show {:uuid (get-in req [:params :schema])})))

(defn wrap-allowed-to-write []
  (schema-middleware/write-permission-middleware!
   #(or (get-in % [:params :schema])
        (get-in % [:route-params :schema])
        (-> (get-in % [:route-params :uuid])
            (domain/schema-of!)
            :uuid))))

(defroutes write-routes
  (POST (register! :attribute-new "/attribute/new") []
        new!)
  (POST (register! :attribute-edit "/attribute/edit/:schema")
        [schema :as req]
        (edit! schema req))
  (DELETE (register! :attribute-delete "/attribute/:uuid/delete")
          [uuid :as req]
          (delete! uuid req)))

(defroutes routes
  (comp/wrap-routes write-routes
                    (wrap-allowed-to-write)))
