             [clojure.contrib.str-utils2 :as s])
   (:import com.google.appengine.api.datastore.EntityNotFoundException))
 
-(ds/defentity Page [^:key title, body])
+(ds/defentity Page [^:key url, title, body, timestamp])
 
 (defn canonical-title
   "Converts a given page title to a standard format, suitable for use in a URL."


(defn render-page
  "Retrieve a page from the datastore and render it for display to the user"
  [title]
  (try
    (response-wrapper title (:body (ds/retrieve Page title)))
    (catch EntityNotFoundException _
      (response-wrapper "404" (str "Unable to find page: " title) 404))))

(defn add-or-edit-form
  "Returns a form to add or edit a page."

   "All Pages"
   (for [page pages]
     [:div [:h1 (:title page)]
      [:div (:body page)]])))

(defn render-paginate
  "Renders a fixed number of pages"
  [number]
  (def pagesize 10)
  (def pages (ds/query :kind Page :limit pagesize
                       :offset (* pagesize number)
                       :sort [[:timestamp :dsc]]))
  (response-wrapper
   "Paginated"
   (html (for [page pages]
           [:div [:h1 (:title page)]
            [:div (:body page)]])
         (if (> number 0)
           (html (link-to (str "/pages/" (dec number)) "prev") [:br]))
         (if (= pagesize (count pages))
           (link-to (str "/pages/" (inc number)) "next")))))

(defroutes ackbar-app-handler
  (GET "/" [] (render-paginate 0))
  (GET "/pages/:number" [number] (render-paginate (Integer/parseInt number)))
  (GET "/admin/add" [] (admin-add-page))
  (GET "/admin/pages" [] (admin-page-list))
  (POST "/admin/add" {params :params}
        (add-page (canonical-title (params "title"))
                  (params "title")
                  (params "body")))
  (GET "/admin/edit/:title" [title] (admin-edit-page title))
  (POST "/admin/edit" {params :params}
        (edit-page (canonical-title (params "title"))
                  (params "title")
                  (params "body")))
  (POST "/admin/delete/:title" [title] (delete-page title))
  (GET "/pages" [] (all-pages))
  (GET "/:title" [title] (render-page (canonical-title title)))
  (ANY "*" [] (response-wrapper "404" "NOT FOUND!" 404)))

