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

(defn edit [instance form form-data schemas req]
  (view/layout
    :request req
    :content
    [[:h1
      (h (-> instance :schema :name))
      "&nbsp;"
      [:small (h (:name instance))]]
     [:p [:small
          [:a {:href (path :instance-list
                           {:schema-uuid (-> instance :schema :uuid)})}
           "Back to List"]
          " | "
          [:a {:href (path :instance-show instance)}
           "Back to Instance"]]]
     [:section.edit-instance
      [:h2 "Edit Instance"]
      (hform/form-to [:post (path :instance-edit instance)]
                     (form/render-widgets form form-data req)
                     (hform/submit-button "Edit!"))
      (hform/form-to [:delete (path :instance-delete instance)]
                     (anti-forgery-field)
                     (view/delete-btn))]
     (when (seq (:links-out instance))
       [:section.links-out
        [:h2 "Outgoing Links"]
        [:table
         [:thead
          [:tr
           [:th "Name"]
           [:th "Instance"]
           [:th "Schema"]
           [:th "Created"]
           [:th]]]
         [:tbody
          (for [{:keys [link target schema]} (:links-out instance)
                :let [name (:name link)
                      empty (empty? name)
                      name (if empty [:i "empty"] (h name))]]
            [:tr
             [:td name]
             [:td [:a {:href (path :instance-show target)}
                   (h (:name target))]]
             [:td [:a {:href (path :instance-list
                                   {:schema-uuid (:uuid schema)})}
                   (h (:name schema))]]
             [:td (prettify-dt (:created_at link))]
             [:td (hform/form-to [:delete (path :instance-link-delete
                                                {:uuid (:uuid instance)
                                                 :link-uuid (:uuid link)})]
                                 (anti-forgery-field)
                                 (view/delete-btn))]])]]])
     (when (seq (:tags instance))
       [:section.tags
        [:h2 "Tags"]
        (view-tag/tag-table instance)])
     [:section.link-instance
      [:h2 "Link Instance with Instance of Schema..."]
      [:ul
       (for [schema schemas]
         [:li
          [:a {:href (path :instance-link-selection
                           {:uuid (:uuid instance)
                            :schema-uuid (:uuid schema)})}
           (h (:name schema))]])]]]))
