(ns yenu.routes.auth
  (:require [yenu.layout :as layout]
            [compojure.core :refer [defroutes GET POST]]
            [yenu.config :refer [env]]
            [ring.util.response :refer [redirect]]))

(defn valid-identity [password]
  (cond
    (= password (:creator-password env)) :creator
    (= password (:user-password env)) :user))

(defn login! [request]
  (let [password (get-in request [:form-params "password"])
        session (:session request)
        user-identity (valid-identity password)
        next-url (get-in request [:params :next] "/page/1")]
    (if user-identity
      (let [updated-session (assoc session :identity user-identity)]
        (-> (redirect next-url)
            (assoc :flash {:message "Login successfull" :type "success"})
            (assoc :session updated-session)))
      (-> (redirect (format "/login?next=%s" next-url))
          (assoc :flash {:message "Wrong password" :type "danger"})))))

(defn logout! [request]
  (-> (redirect "/login")
      (assoc :session {})
      (assoc :flash {:message "Logout successfull" :type "success"})))

(defroutes auth-routes
  (GET "/login" [:as request]
       (layout/render-file "login.html", {:flash (:flash request)}))
  (POST "/login" [] login!)

  (GET "/logout" [] logout!))
