(ns com.oly.static-sites.clojure-demos.sitemap
  (:require [clojure.data.xml :as xml]
            [com.oly.static-sites.clojure-demos.routes :refer [routes]]))

;; Warning here be macro magic to build the sitemap.

(defn pwa-sitemap [domain routes]
     (xml/indent-str
        {:tag :urlset
         :attrs {:xmlns "http://www.sitemaps.org/schemas/sitemap/0.9"}
         :content
         (mapv (fn [r]
                 {:tag :url
                  :attrs {}
                  :content [{:tag :loc :attrs {} :content [(str domain r)]}]}
                 ) routes)}))

(defn build-sitemap-urls [routes] 
  (->> routes
       (reduce (fn handle-sitemap [result [route route-map]]
                 (if (-> route-map :sitemap :vec)
                   (conj result ((-> route-map :sitemap :vec)))
                   (conj result route)
                   )) [])
       flatten))

(defmacro spit-pwa-sitemap
  "Generate the sitemap and outut to the provided path"
  [path domain ]
  (clojure.core/spit
   path
   (pwa-sitemap
    domain
    (build-sitemap-urls routes))))


