
// Fridge.java
// Michele Loreti and the jSpace Developers, 2017
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* Example using the tuple operations: 
     put, queryp, getp, and queryAll

   Explained at:
    https://github.com/pSpaces/Programming-with-Spaces/blob/master/tutorial-tuple-spaces.md

  Usage:
    > compile.bat Fridge.java
    > run.bat Fridge

  Other version: 
    * ConcurrentFridge.java
*/

import java.util.*;

import org.jspace.*;


public class Fridge
{
  public static void main(String[] args) 
                           throws InterruptedException
  {
    // choose one of these spaces:
    Space fridge = new VisSpace();
      /* to speed things up, add a delay argument to VisSpace
         (e.g. VisSpace(1000) for 1 second); the default is 2000 ms
      */
    //Space fridge = new SequentialSpace(); 

    // Add some tuples representing (item, no. of items)
    fridge.put("coffee", 1);
    fridge.put("coffee", 1);   // "coffee" appears twice
    fridge.put("clean kitchen");  // will be treated as a 'request'
    fridge.put("butter", 2);
    fridge.put("milk", 3);

    // Look for the cleaning request
    Object obj = fridge.queryp(new ActualField("clean kitchen"));
    if (obj != null) {
      System.out.println("We need to clean the kitchen");
       // Remove the request tuple
       obj = fridge.getp(new ActualField("clean kitchen"));
    }
    else
      System.out.println("No need to clean");

    // Look for a 'milk' tuple
    Object[] objs =
         fridge.queryp( new ActualField("milk"), 
                        new FormalField(Integer.class));
    if (objs != null) {
      int numBottles = (int)objs[1];
      if (numBottles < 10) {
        System.out.println("We better buy milk");
        // remove the 'milk' tuple
        objs = fridge.getp( new ActualField("milk"), 
                            new FormalField(Integer.class));
        fridge.put("milk", numBottles+1);  // update the space
        System.out.println("- one bottle bought");
      }
      else
        System.out.println("We have enough milk");
    }

    // read all the items in the fridge
    List<Object[]> groceryList = fridge.queryAll(
                           new FormalField(String.class),
                           new FormalField(Integer.class));
    System.out.println("Fridge items: ");
    for (Object[] g : groceryList)
      System.out.println("  " + Arrays.toString(g));
  } /* main */


}  // end of Fridge class
