(ns yenu.routes.feed
  (:require [hiccup.core :as h]
            [compojure.core :refer [defroutes GET]]
            [clj-time.format :as time-format]
            [clj-time.core :as time]
            [yenu.config :refer [env]]
            [yenu.layout :refer [render]]
            [yenu.db.core :as db])
  (:use [markdown.core]))

(defn rss-feed []
  (let [entries (db/get-all-images {:offset 0 :count 25})
        with-ts #(time/to-time-zone (time-format/parse %) (time/default-time-zone))]
    (str
     "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
     (h/html
      [:feed {:xmlns "http://www.w3.org/2005/Atom"}
       (for [a (:authors env)] [:author [:name a]])
       [:title "yenu -- the image sharing tool for friends"]
       [:id (str (:basepath env))]
       [:updated (with-ts (:created_at (first entries)))]
       (for [e entries]
         [:entry
          [:title (h/h (:title e))]
          [:link {:href (str (:basepath env) "/show/" (:id e)) :rel "alternate"}]
          [:id (str (:basepath env) "/show/" (:id e))]
          [:updated (with-ts (:created_at e))]
          [:summary (h/h (:title e))]
          [:content {:type "xhtml"}
           [:div {:xmlns "http://www.w3.org/1999/xhtml"}
            (md-to-html-string (h/h (:description e)))]]])]))))

(defroutes feed-routes
  (GET "/feed" []
       (render (rss-feed) "text/xml")))
