(ns wanijo.tag.view
  (:require [hiccup.form :as hform]
            [hiccup.core :refer [h]]
            [ring.util.anti-forgery :refer [anti-forgery-field]]
            [formulare.core :as form]
            [wanijo.tag.forms :as forms]
            [wanijo.infrastructure
             [routing :refer [path]]
             [view :as view]
             [time :refer [prettify-dt]]]))

(defn tag->html [tag]
  [:span.single-tag
   [:code ":" (h (:name tag))]])

(defn tag-list [tags]
  [:ul.tag-list
   (for [tag tags]
     [:li
      (tag->html tag)])])

(defn new-tag-form [{uuid :uuid}]
  (list
    (hform/form-to [:post (path :tag-create {:instance-uuid uuid})]
                   (form/render-widgets forms/new-tag {} {})
                   (hform/submit-button "Tag!"))
    [:small (str "Comma separate each tag. "
                 "Tag names must not contain whitespace.")]))

(defn tag-table [{tags :tags
                  instance-uuid :uuid}]
  [:table
   [:thead
    [:tr
     [:th "Name"]
     [:th "Created"]
     [:th]]]
   [:tbody
    (for [tag tags]
      [:tr
       [:td (tag->html tag)]
       [:td (prettify-dt (:created_at tag))]
       [:td (hform/form-to [:delete (path :tag-remove
                                          {:uuid (:uuid tag)
                                           :instance-uuid instance-uuid})]
                           (anti-forgery-field)
                           (view/delete-btn))]])]])
