; @UIService ui

(ns lymphatic-junctions.scripts.quantify-classes
    (:require [fun.imagej.table :as table]
      [clojure.string :as string]
      [fun.imagej.imp.roi :as roi]
              [lymphatic-junctions.globals :as globals]))

(refer 'user)

(let [roi-manager (ij.plugin.frame.RoiManager/getRoiManager)
      rois (seq (.getRoisAsArray roi-manager))
      tbl (table/create-table)
      classname-col (table/create-column "Class")
      count-col (table/create-column "Count")
      area-col (table/create-column "Area")
      roi-names (map #(.getName %) rois); filter to ensure they are ROIs, not exclusions
      roi-classes (map #(read-string (last (string/split % #"_"))) roi-names)]

     (doseq [classname (keys globals/class-coloring)]
            (let [class-pairs (filter #(= (globals/class-coloring classname)
                                         (first %))
                                     (map list roi-classes (range)))
                  class-rois (map #(nth rois (second %)) class-pairs)]
                 (table/add-to-column classname-col (name classname))
                 (table/add-to-column area-col (reduce + (map roi/area class-rois)))
                 (table/add-to-column count-col (count class-rois))))


     (table/add-column-to-table tbl classname-col)
     (table/add-column-to-table tbl count-col)
     (table/add-column-to-table tbl area-col)

     (.show ui tbl)

     (intern 'user 'class-table tbl))

