 (ns salava.badge.ui.evidence
   (:require [salava.core.ui.modal :as mo]
             [reagent.core :refer [cursor atom]]
-            [salava.core.i18n :refer [t]]
+            [salava.core.i18n :refer [t translate-text]]
             [reagent.session :as session]
             [salava.core.ui.helper :refer [plugin-fun path-for hyperlink base-url]]
             [salava.core.ui.ajax-utils :as ajax]
             [salava.core.time :refer [date-from-unix-time]]
-            [clojure.string :refer [blank? includes?]]
-            [salava.file.icons :refer [file-icon]]))
+            [clojure.string :refer [blank? includes? split trim]]
+            [salava.file.icons :refer [file-icon]]
+            [salava.file.ui.my :refer [send-file]]))
+
+(defn url? [s]
+  (when-not (blank? s)
+    (not (blank? (re-find #"^http" (str (trim s)))))))
 
 (defn input [input-data textarea?]
   (let [{:keys [name atom placeholder type error-message-atom rows cols]} input-data]

      :placeholder placeholder
      :on-change   #(do
                      (reset! atom (.-target.value %))
                      (if error-message-atom(reset! error-message-atom (:message "")))
                      )
      :value       @atom
      :rows rows
      :cols cols}]))

#_(defn input [input-data textarea?]
   (let [{:keys [name atom placeholder type error-message-atom rows cols]} input-data
         opt-map (merge input-data {:class "form-control"
                                    :id (str "input-" name)
                                    :value @atom
                                    :on-change #(do
                                                  (reset! atom (.-target.value %))
                                                  (if error-message-atom(reset! error-message-atom (:message ""))))})]
     [(if textarea? :textarea :input) opt-map]))


(defn toggle-input-mode [key state url?]
  (let [key-atom (cursor state [key])]
    (do
      (if url? (swap! state assoc :resource_input false) (swap! state assoc :url_input false))
      (if @key-atom (swap! state assoc key false) (swap! state assoc key true) ))))

(defn init-user-pages [resource-atom]
  (ajax/GET
    (path-for "/obpv1/page" true)
    {:handler (fn [data]
                (swap! resource-atom assoc :pages data)
                )}))

(defn init-user-files [resource-atom]
  (ajax/GET
    (path-for "/obpv1/file" true)
    {:handler (fn [data]
                (swap! resource-atom assoc :files data)
                )}))

(defn init-resources [resource-atom]
  (do
    (init-user-pages resource-atom)
    (init-user-files resource-atom)))

(defn toggle-selected [resource coll]
  (if (contains? @coll resource)
    (reset! coll (disj @coll resource))
    (swap! coll conj resource)))

(defn resource-grid-element [element-data type coll]
  (let [{:keys [id name path visibility mtime badges ctime mime_type]} element-data
        page-url (str (session/get :site-url) (path-for (str "/page/view/" id)))
        checked? (if-not (blank? path)
                   (boolean (some #(= path %) @coll))
                   (boolean (some #(= page-url %) @coll) )) ]
    [:div.checkbox
     [:input {:id (str "input-" name)
              :type "checkbox"
              :on-change #(do (toggle-selected (.-target.value %) coll ))
              :value (case type
                       :page page-url
                       :file path)
              :checked checked?
              }]
     (case type
       :page [:a {:href "#" :on-click #(do
                                         (.preventDefault %)
                                         (mo/open-modal [:page :view] {:page-id id}))} name]

       :file [:div [:i {:style {:margin-right "10px"}
                        :class (str "file-icon-large fa " (file-icon mime_type))}]
              [:a {:href (str "/" path) :target "_blank"} name]])]))

(defn selected-resources-block [selected-resources-atom]
  (fn []
    [:div
     (reduce (fn [coll resource]
               (conj coll [:p (hyperlink resource)])
               ) [:div] @selected-resources-atom)
     [:br]]))

(defn toggle-visible-area [visible-area-atom key]
  (if (= key @visible-area-atom) (reset! visible-area-atom nil) (reset! visible-area-atom key)))


(defn resources-grid [state]
  (let [resource-atom (atom {:pages [] :files [] :visible_area nil})
        visible-area-atom (cursor state [:visible_area])
        selected-resources-atom (atom #{})]
    (init-resources resource-atom)
    (fn []
      (let [{:keys [pages files]} @resource-atom
            files (:files files)]
        [:div#badge-stats
                   (when-not (empty? @selected-resources-atom)
        [selected-resources-block selected-resources-atom])
         [:div.panel
          [:div.panel-heading
           [:h3 [:a {:href "#" :on-click #(do (.preventDefault %) (toggle-visible-area visible-area-atom :pages))}(str (t :page/Pages) " : " (count pages))]]]
          (if (= @visible-area-atom :pages)
            (reduce (fn [r p]
                      (conj r
                            [resource-grid-element p :page selected-resources-atom])) [:div.panel-body] pages))
          ]
         [:div.panel
          [:div.panel-heading
           [:h3 [:a {:href "#" :on-click #(do (.preventDefault %) (toggle-visible-area visible-area-atom :files))} (str (t :page/Files) " : " (count files))]]]
          (if (= @visible-area-atom :files)
            (reduce (fn [r p]
                      (conj r
                            [resource-grid-element p :file selected-resources-atom])) [:div.panel-body] files)
            )
          ]]
        )
      )
    ))


(defn evidence-form [data state init-data]

        evidence-audience-atom (cursor state [:evidence :audience])
        evidence-genre-atom (cursor state [:evidence :genre])
        evidence-url-atom (cursor state [:evidence :url])
        evidence-narrative-atom (cursor state [:evidence :narrative])
        page-input-enabled? (cursor state [:page_input])
        message (cursor state [:evidence :message])
        show-url? (cursor state [:evidence :show_url])
        file-input-enabled? (cursor state [:file_input])
        resource-input-mode (cursor state [:input_mode])
        show-form (cursor state [:show_form])
        {:keys [image_file name]} data]

    [:div {:id "badge-settings" :class "row flip"}
     [:div {:class "col-md-3 badge-image modal-left"}
      [:img {:src (str "/" image_file) :alt name}]]
     [:div {:class "col-md-9 settings-content settings-tab"}
      (if @message [:div @message])
      [:div
       [:div.form-horizontal
        [:div.form-group
         [:label.col-md-3 "Add evidence page"]
         [:div.col-md-9 {:style {:margin-top "10px" :margin-bottom "10px"}}
          ;[:div {:style {:float "left" :margin-right "10px"}} [:i.fa.fa-plus]]
          [:div {:style {:float "left"}}
           [:div {:style {:float "left" :margin-right "10px"}}[:a {:style {:margin "10px"} :href "#"  :on-click #(toggle-input-mode :url_input state)} [:i.fa.fa-link] (t :admin/Url)]]
           [:div {:style {:float "left" :margin-right "10px"}} [:a {:href "#" :on-click #(do (toggle-input-mode :page_input state)
                                                                                           #_(swap! state assoc :tab [resource-tab data state init-data])
                                                                                           ) } [:i.fa.fa-file] (t :page/Mypages)]]
           [:div {:style {:float "left"}} [:a {:href "#"
                                               :on-click #(do
                                                            (.preventDefault %)
                                                            (toggle-input-mode :file_input state))
                                               } [:i.fa.fa-file] (t :page/Files)]]]]

         [selected-url state init-data]
         [resource-input state]]

        (if @show-form
          [:div
           [:div.form-group
            [:label.col-md-3 "Name"]
            [:div.col-md-9
             [input {:name "name" :atom evidence-name-atom :placeholder "input a name" :type "text"} nil]]]
           [:div.form-group
            [:label.col-md-3 "Audience"]
            [:div.col-md-9
             [input {:name "audience" :atom evidence-audience-atom :placeholder "" :type "text"} nil]]]
           [:div.form-group
            [:label.col-md-3 "Genre"]
            [:div.col-md-9
             [input {:name "genre" :atom evidence-genre-atom :placeholder "" :type "text"} nil]]]

           [:div.form-group
            [:label.col-md-3 (t :page/Description)]
            [:div.col-md-9
             [input {:name "Description" :rows 5 :cols 40 :atom evidence-description-atom } true]]]

           [:div.form-group
            [:label.col-md-3 (t :badge/Narrative)]
            [:div.col-md-9
             [input {:name "Narrative" :rows 5 :cols 40 :atom evidence-narrative-atom } true]]]
           ]
          [:div
           [:a {:href "#" :on-click #(do (.preventDefault %) (reset! show-form true))} "Add more info about this evidence"]])
                   [:div
            [:button {:type         "button"
                      :class        "btn btn-primary"
                      :on-click     #(save-badge-evidence data state init-data)}
             (t :badge/Save)]
            [:button {:type "button"
                      :class "btn btn-primary"
                      :on-click #(do (.preventDefault %) (swap! state assoc :tab [settings-tab (dissoc data :evidence) state init-data] :tab-no 2))}
             (t :core/Cancel)]]]]]]))

(defn delete-evidence! [id data state init-data]
  (let [init-settings (first (plugin-fun (session/get :plugins) "modal" "show_settings_dialog"))]
    (ajax/DELETE
      (path-for (str "/obpv1/badge/evidence/" id))
      { :params {:user_badge_id (:id data)}
        :handler (fn [r]
                   (if (= "success" (:status r))
                     (init-settings (:id data) state init-data "settings")
                     ;(swap! state assoc :tab [settings-tab data state init-data] :tab-no 2)
                     )
                   )}
      )
    ))

#_(defn evidence-list [data state init-data]
    (reduce (fn [r evidence]
              (let [{:keys [genre description narrative name audience id url mtime ctime]} evidence]
                (conj r
                      [:div.col-md-9.evidence-block
                       [:a {:href "#" :on-click #(do (.preventDefault %)
                                                   (init-evidence-form evidence state true)
                                                   (swap! state assoc :tab [evidence-form data #_(assoc data :evidence evidence) state init-data]))}
                        [:div [:div {:style {:float "left"}} [:i.fa.fa-link]]  url]
                        (if name [:div.inline [:label (t :badge/Name) ": "] name])
                        (if narrative [:div [:label (t :badge/Narrative) ": "] narrative])
                        (if description [:div [:label (t :admin/Description) ": "]  description])
                        (if genre [:div [:label (t :badge/Genre) ": "] genre])
                        (if audience [:div [:label (t :badge/Audience) ": "] audience])
                        ]
                       [:button {:type "button"
                                 :aria-label "OK"
                                 :class "close"
                                 :on-click #(delete-evidence! id data state init-data)}
                        [:span {:aria-hidden "true"
                                :dangerouslySetInnerHTML {:__html "&times;"}}]]
                       ])
                )) [:div.evidence-list] (:evidences data)))

(defn evidence-list [data state init-data]
  (reduce (fn [r evidence]
            (let [{:keys [genre description narrative name audience id url mtime ctime]} evidence]
              (conj r
                    [:div.panel.panel-default
                     [:div.panel-heading {:id (str "heading" id)
                                          :role "tab"}
                      [:div.panel-title
                       [:a {:href "#" :on-click #(do (.preventDefault %)
                                                   (init-evidence-form evidence state true)
                                                   (swap! state assoc :tab [evidence-form data state init-data] :show_form true))}
                        [:div [:div {:style {:float "left"}} [:i.fa.fa-link]]  url]]
                       (if (or genre description narrative name audience)
                         [:div.show-more [:a {:role "button" :data-toggle "collapse"
                          :data-parent "#accordion"
                          :href (str "#collapse" id)
                              :aria-expanded "true"
                              :aria-controls (str "collapse" id)} "show more"]]
                         )
                       ]
                                             [:div [:button {:type "button"
                                 :aria-label "OK"
                                 :class "close panel-close"
                                 :on-click #(delete-evidence! id data state init-data)}
                        [:span {:aria-hidden "true"
                                :dangerouslySetInnerHTML {:__html "&times;"}}]]]
                      ]
                     (if (or genre description narrative name audience)
                     [:div {:id (str "collapse" id)
                            :class "panel-collapse collapse"
                            :role "tabpanel"
                            :aria-labelledby (str "heading" id)}
                      [:div.panel-body
                       (if name [:div.inline [:label (t :badge/Name) ": "] name])
                        (if narrative [:div [:label (t :badge/Narrative) ": "] [:div narrative]])
                        (if description [:div [:label (t :admin/Description) ": "]  [:div description]])
                        (if genre [:div [:label (t :badge/Genre) ": "] genre])
                        (if audience [:div [:label (t :badge/Audience) ": "] audience])
                       ]])])
              )
            )[:div {:id "accordion" :class "panel-group evidence-list" :role "tablist" :aria-multiselectable "true"}] (:evidences data)))

(defn evidence-block [data state init-data]
  [:div#badge-settings
   [:div.form-group
    [:label {:class "col-md-12 sub-heading" :for "evidence"} (t :badge/Evidence)]


    [:div.col-md-9 {:class "new-evidence"}
     [:i.fa.fa-plus-square.fa-sm]
     [:a {:href "#" :on-click #(do (.preventDefault %)
                                 (swap! state assoc :evidence nil)
                                 (swap! state assoc :tab [evidence-form data state init-data] :tab-no 2))} (t :badge/Addnewevidence)]]]

   [:div.form-group
    [:div.col-md-9 [evidence-list data state init-data]]]
   ])

(defn evidence-modal [state]
  (fn []
