
package AOMCase;

import com.metamaxim.modelscope.callbacks.*;

public class ResourceFinder {

  public static void seekResource(Event trigger, Instance thisMission) {

  //This method tries to find a Resource that:
  //    -   is suitable for this Mission and
  //    -   has not been already requested for this Mission
  //If it finds one, it creates a Request for assignment to the Mission.

      // Check that the Mission is not Accomplished.
      if (!thisMission.getString("Mission Status").equals("confirmed"))
      	return;
	  Instance thisMissonType = thisMission.getInstance("Mission Type");
	  // Get all the Resources who have the right Expertise for this Mission
	  Instance[] myPossibleResources = thisMissonType.selectByRef("Mobile Employee", "Expertise");
	  // Get all the Requests that have already been made for this Mission
	  Instance[] oldRequests = thisMission.selectByRef("Assignment Request", "For Mission");

	  for (int i = 0; i < myPossibleResources.length; i++) {
		  // Check if the Resource is available
		  if (myPossibleResources[i].getState("Internal Resource").equals("available")) {
			  //Check if the Resource has already been requested for this Mission (to avoid doing it again!)
			  boolean alreadyRequested = false;
			  for (int j = 0; j < oldRequests.length; j++) {
				  if (oldRequests[j].getInstance("Internal Resource").equals(myPossibleResources[i])) {
					  alreadyRequested = true;
				  	  }
			  	  }
			  // If available and not already requested, create a Request and finish
			  if (!alreadyRequested) {
				  Event requestAssignment = trigger.createEvent("Request Assignment");
				  requestAssignment.setNewInstance("Assignment Request", "Assignment Request");
				  requestAssignment.setInstance("Internal Resource", myPossibleResources[i]);
				  requestAssignment.setInstance("For Mission", thisMission);
				  requestAssignment.submitToModel();
		  	  	  return;
		  	  	  }
	  	   	  }
		}
	}

}
