;; Copyright © 2014-2017, JUXT LTD.

(ns yada.resources.url-resource
  (:require
   [ring.util.mime-type :refer [ext-mime-type]]
   [yada.charset :as charset]
   [yada.resource :refer [resource ResourceCoercion]]
   [yada.util :refer [as-file]])
  (:import [java.io BufferedReader InputStreamReader]
           java.net.URL
           java.util.Date))

;; A UrlResource is a Java resource on the classpath.

(extend-type URL
  ResourceCoercion
  (as-resource [url]
    (resource
     {:properties
      (fn [ctx]
        (merge {}
               (when-let [f ^java.io.File (as-file url)]
                 (when (.exists f)
                   {:last-modified (Date. (.lastModified f))}))))

      :methods
      {:get
       {:produces
        [{:media-type #{(or (ext-mime-type (.getPath url))
                            "application/octet-stream")}
          :charset charset/platform-charsets
          }]
        :response
        (fn [ctx]
          (if (= (get-in ctx [:response :representation :media-type :type]) "text")
            (BufferedReader.
             ;; Is the resource coded in a different charset? Can't use
             ;; default coercion, supply a custom resource.
             (InputStreamReader. (.openStream url) "UTF-8"))
            (.openStream url)))}}})))
