 (ns reports.scheduler
   (:refer-clojure :exclude [key])
-  (:import [org.quartz JobExecutionContext Scheduler])
+  (:import [org.quartz JobExecutionContext Scheduler]
+           java.io.File)
   (:require [clojure.string :as string :only (split join)]
             [clojurewerkz.quartzite [conversion :as conversion]
                                     [jobs :as jobs]

        (doseq [key (keys @cache) :when (and (= (:baseURL key) baseURL) (= (str sid) (:surveyId key)))]
        (alter cache dissoc key))))
    "OK"))


(def cache (ref {}))

(defn- valid-report? [report-path]
  "Returns if a File is a valid one (exists and non zero length)"
  (if (and (.exists ^File report-path)
           (> 0 (.length ^File report-path)))
    true false))

(defn- get-path [report-file]
  "Returns the path to the report or `INVALID_PATH` if not valid File"
  (if (valid-report? report-file)
    (string/join "/" (take-last 2 (string/split (.getAbsolutePath ^File report-file) #"/")))
    "INVALID_PATH"))

(jobs/defjob ExportJob [job-data]
  (let [{:strs [baseURL exportType surveyId opts reportId]} (conversion/from-job-data job-data)
        report (export-report exportType baseURL surveyId opts)
        path (get-path report)]
    (dosync
      (alter cache conj {{:id reportId
                          :surveyId surveyId
