 (defn job-instances-for-stage-instance [{pipeline-run :pipeline_counter
                                          stage-run :counter
                                          jobs :jobs}]
-  (map (fn [{id :id name :name result :result scheduled-date :scheduled_date}]
+  (map (fn [{id :id name :name scheduled-date :scheduled_date}]
          {:jobId id
           :jobName name
           :stageRun stage-run
           :pipelineRun pipeline-run
           :scheduledDateTime (tc/from-long scheduled-date)})
        jobs))
+
+(defn job-instance-for-accumulated-stage-instance [{pipeline-run :pipeline_counter
+                                                    stage-run :counter
+                                                    jobs :jobs}]
+  (let [job-instances (map (fn [{id :id name :name}]
+                             {:jobId id :jobName name})
+                           jobs)]
+    {:jobId 0
+     :jobName "accumulated"
+     :stageRun stage-run
+     :pipelineRun pipeline-run
+     :scheduledDateTime (tc/from-long (apply min (map :scheduled_date jobs)))
+     :jobs-for-accumulation job-instances}))
+
+(defn fetch-job-instances-for-stage-instance [accumulate-stages-for-pipelines stage-name stage-instance]
+  (if (contains? accumulate-stages-for-pipelines stage-name)
+    (list (job-instance-for-accumulated-stage-instance stage-instance))
+    (job-instances-for-stage-instance stage-instance)))
 
 (defn get-stage-instances [pipeline stage-name offset]
   (let [stage-history (get-json "/api/stages/%s/%s/history/%s" pipeline stage-name offset)

   ["-f" "--from DATE" "DATE from which on builds are loaded (by default tries to pick up where the last run finished)"
    :id :load-builds-from
    :parse-fn #(tf/parse date-formatter %)]
   ["-h" "--help"]])

;; util

  (let [build (get-json "/jobStatus.json?pipelineName=&stageName=&jobId=%s" jobId)]
    (parse-build-info build)))

(defn accumulate-builds [builds]
  (let [outcomes (map :outcome builds)
        start-times (map :start builds)
        end-times (map :end builds)]
    {:start (apply min start-times)
     :end (apply max end-times)
     :outcome (if (every? #(= "pass" %) outcomes)
                "pass"
                "fail")}))

(defn build-for-job [job-instance]
  (if-let [jobs-for-accumulation (:jobs-for-accumulation job-instance)]
    (let [builds (map build-for jobs-for-accumulation)]
      (accumulate-builds builds))
    (build-for job-instance)))

(defn job-data-for-instance [jobInstance]
  (assoc jobInstance :build (build-for-job jobInstance)))


;; /api/stages/%pipeline/%stage/history
