 (ns gbu.webhook
   (:require [clojure.data.json :as json]
+            [clojure.java.io :as io]
             popen)
   (:import java.io.File))
 

  [url sha]
  (let [path       (make-tmp-dir)
        clone      (popen/popen ["git" "clone" url path] :redirect true :dir ".")
        _          (popen/join clone)
        checkout   (popen/popen ["git" "checkout" sha] :redirect true :dir path)
        _          (popen/join checkout)]
    path))

(defn- run-eastwood 
  [path]
  (let [lein      (popen/popen ["lein" "eastwood" "{:results-file true}"] :redirect true :dir path)
        code      (popen/join lein)]
    (when-not (zero? code)
      (let [results-txt (slurp (str path "/eastwood-results.txt"))]
        (read-string (str "[" results-txt "]"))))))

(defn- handle-pull-req 
  [pr-event]
  (let [pull-req  (:pull_request pr-event)
        sha       (get-in pull-req [:head :sha])
        repo      (:repo pull-req)
        url       (:clone_url repo)
        path      (clone-repo url sha)
        result    (run-eastwood path)]
    ()))

(defmulti handle-event ^:private
  (fn [event-type _] (keywordize event-type)))

(defn run
  [event-type event-raw]
  (let [event (and (seq event-raw)
                   (json/read-str event-raw))]
    (handle-event event-type event)))

(defmethod handle-event :ping
  [_ event]

  [_ event]
  (future (handle-pull-req event))
  {:status 200
   :body "Your PR is being processed..."})

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API

(defn run
  [event-type event-raw]
  (let [event (and (seq event-raw)
                   (json/read-str event-raw :key-fn keyword))]
    (handle-event event-type event)))
