 (ns clj-gatling.core
+  (:use [clojure.set :only [rename-keys]])
   (:import (io.gatling.charts.report ReportsGenerator)
            (io.gatling.charts.result.reader FileDataReader)
            (io.gatling.core.config GatlingConfiguration))

    (GatlingConfiguration/setUp conf)
    (ReportsGenerator/generateFor "out" (FileDataReader. "23"))))

(defn map-request [line]
  (let [start (.toString (:start line))
        end (.toString (:end line))]
    ["REQUEST" "Scenario name" (.toString (:id line)) "" "request_1" start start "1390591841245" end "OK" "\u0020"]))

(defn map-scenario [line]
  (let [start (.toString (:start line))
        end (.toString (:end line))]
    ["SCENARIO"	"Scenario name"	(.toString (:id line)) start end]))

(defn create-result-lines [result]
  (let [header ["RUN" "20140124213040" "basicexamplesimulation" "\u0020"] 
        reqs-and-scenarios (apply concat (map #(vector (map-request %) (map-scenario %)) result))]
    (conj reqs-and-scenarios header)))

(defn -main [threads]
  (let [result (run-simulation (read-string threads))

            [clojure-csv.core :as csv])
  (:gen-class))

(def test-scenario {:requests ["Request1" "Request2"]})

(defmacro bench [expr]
  `(let [start# (System/currentTimeMillis)
         result# ~expr]
      {:result result# :start start# :end (System/currentTimeMillis) }))

(defn run-request [name id]
  ;(println (str "Simulating request for " id))
  (Thread/sleep (rand 1000))
  "OK")

(defn run-scenario [scenario id]
  (assoc
    (rename-keys 
      (bench
        (map #(assoc (bench (run-request % id)) :name % :id id) (:requests scenario)))
      {:result :requests})
    :id id))

(defn run-simulation [threads]
  (println (str "Run simulation with " threads " threads"))
  (let [cs (repeatedly threads async/chan)
        ps (map vector (iterate inc 0) cs)]
    (doseq [[i c] ps] (go (>! c (run-scenario test-scenario i))))
    (let [result (for [i (range threads)]
      (let [[v c] (async/alts!! cs)]
        v))]
