(ns wanijo.instance.view.instances
  (:require [hiccup.form :as hform]
            [hiccup.core :refer [h]]
            [formulare.core :as form]
            [wanijo.instance.view.view :as view-instance]
            [wanijo.infrastructure.view :as view]
            [wanijo.infrastructure.routing :refer [path]]
            [wanijo.infrastructure.time :refer [prettify-dt]]))

(defn instances [schema instances new-form req]
  (view/layout
    :request req
    :content
    [[:h1 "All Instances of schema "
      [:span.schema-title__name (h (:name schema))]]
     [:h1 "New Instance"]
     (hform/form-to [:post (path :instance-new)]
                    (form/render-widgets new-form {} req)
                    (hform/hidden-field "schema-uuid"
                                        (:uuid schema))
                    (hform/submit-button "Create!"))
     [:table
      [:thead
       [:tr
        [:th "Name"]
        (map (fn [attr] [:th (h (:name attr))])
             (:req-attrs schema))
        [:th "Updated"]
        [:th "Created"]]]
      [:tbody
       (for [instance instances]
         [:tr
          [:td
           [:a {:href (path :instance-show instance)}
            (h (:name instance))]
           (view-instance/tags-for-search instance)]
          (map (fn [attr]
                 [:td (->> (:properties instance)
                           (filter #(= (:uuid attr)
                                       (-> % :attribute :uuid)))
                           first
                           :value
                           h)])
               (:req-attrs schema))
          [:td (prettify-dt (:updated_at instance))]
          [:td (prettify-dt (:created_at instance))]])]]]))
