(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.framework.routing :refer [register! path]]
            [wanijo.attribute.domain :as domain]
            [wanijo.schema.view :as schema-view]
            [wanijo.schema.domain :as schema-domain]
            [wanijo.schema.routes :as schema-routes]
            [wanijo.schema.forms :as schema-forms]))

(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-routes/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)))