package org.commcare.modern.engine.cases;

import org.commcare.cases.model.Case;
import org.commcare.cases.query.QueryCache;

import java.util.HashMap;
import java.util.LinkedHashSet;

/**
 * A case group result cache keeps track of different sets of "Bulk" cases which are
 * likely to have data or operations tracked about them (IE: results of a common query which
 * are likely to have further filtering applied.
 *
 * Since these results are often captured/reported before a context is escalated, this cache
 * doesn't directly hold the resulting cached cases themselves. Rather a CaseObjectCache should
 * be used to track the resulting cases. This will ensure that cache can be attached to the
 * appropriate lifecycle
 *
 * Created by ctsims on 1/25/2017.
 */

public class CaseGroupResultCache implements QueryCache {

    private HashMap<String,LinkedHashSet<Integer>> bulkFetchBodies = new HashMap<>();

    public void reportBulkCaseBody(String key, LinkedHashSet<Integer> ids) {
        if(bulkFetchBodies.containsKey(key)) {
            return;
        }
        bulkFetchBodies.put(key, ids);
    }

    public boolean hasMatchingCaseSet(int recordId) {
        return getTranche(recordId) != null;
    }

    public LinkedHashSet<Integer> getTranche(int recordId) {
        for(LinkedHashSet<Integer> tranche: bulkFetchBodies.values()) {
            if(tranche.contains(recordId)){
                return tranche;
            }
        }
        return null;
    }
}

@@ -117,16 +117,54 @@
 ryCache;
+%0Aimport org.commcare.modern.util.Pair;
 %0A%0Aimport
@@ -1261,16 +1261,29 @@
   public
+ Pair%3CString,
  LinkedH
@@ -1297,16 +1297,17 @@
 Integer%3E
+%3E
  getTran
@@ -1338,16 +1338,69 @@
     for(
+String key : bulkFetchBodies.keySet()) %7B%0A            
 LinkedHa
@@ -1421,17 +1421,18 @@
  tranche
-:
+ =
  bulkFet
@@ -1444,19 +1444,17 @@
 ies.
-values()) %7B
+get(key);
 %0A   
@@ -1516,24 +1516,40 @@
   return
+ new Pair%3C%3E(key,
  tranche
 ;%0A      
@@ -1540,16 +1540,17 @@
  tranche
+)
 ;%0A      

Clarify tranche keys for debugging outputs