law(fixedMarket, language(java), refines(govtSpectrumLaw))
portal(govtSpectrumLaw, lawURL(http://winlab.rutgers.edu/~rishabh/govtSpectrumLaw.java1))
//portal(govtSpectrumLaw, lawHash(ED48AEEEF273464DAD36D04C59AB349E))

public class auctionMarket extends Law {

 	public void sent(String source, String message, String dest, String destlaw) {
  	
  	    System.out.println("\nevent: sent in fixedMarket");
  	    
  	    if (message.startsWith("start")) {
  	    	String content = getContentFromMessage(message);
	 	int pos1 = content.indexOf("]");
	 	int pos2 = content.indexOf(",",pos1+2);
	 	String block = content.substring(0,pos1+1);
	 	int price = Integer.parseInt(content.substring(pos1+2,pos2));
	 	doAdd("sale("+block+","+price+")");
  	    }
  	}
  	
  	public void obligationDue(String obligationTerm) {
  		if (obligationTerm.toString().startsWith("timeout")){
  			System.out.println("obligation in fixed market law: "+obligationTerm);
  		 	String block = getContentFromMessage(obligationTerm);
  		 	if (CS.has("sale("+block+",%P)")) {
  		 		String saleTerm = (CS.findT("sale("+block+",%P)")).toString();
  		 		int price = Integer.parseInt(saleTerm.substring(saleTerm.lastIndexOf(",")+1,saleTerm.length()-1));
  		 		doRemove(saleTerm);
  		 		doDeliver(Self,"dealExpired("+block+","+price+")",Self);
  		 	}
  		 }
  	}
 
  	public void arrived(String source, String sourcelaw, String message, String dest) {

        	System.out.println("\narrived event in fixedMarket");
     
        	if (message.startsWith("offer")) {
            		String content = getContentFromMessage(message);
            		int index1 = content.indexOf("]");
            		String block = content.substring(0,index1+1);
            		int price = Integer.parseInt(content.substring(index1+2,content.length()));
            		if (CS.has("sale("+block+","+price+")")) {
            			doRemove("sale("+block+","+price+")");
            			doRepealObligation("timeout("+block+")");
            			doRemove("timeout("+block+")");
            			doForward(Self,"succeeded("+content+")",source);
            			doDeliver(Self,"winner("+block+","+price+","+source+")",Self);
            		}
            		else {
            			doForward(Self,"rejected("+block+","+price+")",source);
            		}
            	}
        }
 
 
    
     
       /**
           Helper method to parse the argument out of a regular expression
       */
      public String getContentFromMessage(String anyMessage) { 

        int index = anyMessage.indexOf("("); 

        if (index == -1) return ""; 
        else return anyMessage.substring(index+1, anyMessage.length()-1); 
     }
        
       
}

