(ns auto-ap.views.components.dropdown
  (:require [reagent.core :as r]
            [auto-ap.events :as events]
            [auto-ap.views.utils :refer [appearing]]
            [re-frame.core :as re-frame]
            [auto-ap.subs :as subs]))

(defn drop-down-contents [{:keys [id]}]
  (let [toggle-fn (fn [] (re-frame/dispatch [::events/toggle-menu id]))]
    (r/create-class {:component-did-mount (fn [] (.addEventListener js/document "click" toggle-fn))
                           :component-will-unmount (fn [] (.removeEventListener js/document "click" toggle-fn))
                           :reagent-render
                           (fn [children]
                             children)})))

(defn drop-down [{:keys [ id ]} _]
  (let [_ (re-frame/subscribe [::subs/menu-active? id])]
    (r/create-class
     {:reagent-render (fn [{:keys [header id is-right? class] :or {is-right? true}} child]
                        (let [menu-active? @(re-frame/subscribe [::subs/menu-active? id])]
                          [:div.dropdown {:class (str (if menu-active?
                                                                 "is-active"
                                                                 "") " "
                                                               (if is-right?
                                                                 "is-right"
                                                                 "")
                                                               " "
                                                               class)}
                           [:div.dropdown-trigger  header]
                           
                           [appearing {:visible? menu-active? :enter-class "appear" :exit-class "disappear" :timeout 200}
                            [:div.dropdown-menu {:role "menu"}
                             [:div.dropdown-content
                              (when menu-active?
                                [drop-down-contents {:id id}
                                 child])]]]]))})))

