
/* Sample OAA Agent

   This tiny agent sample agent could be a shell for an agent wrapper around
   a fax program.  It publishes the solvable "fax(Dest, Document)" and sets
   up a callback to handle these requests.
*/

package test;

/* Include dependencies */
import java.awt.*;
import java.awt.event.*;
import oaa.agents.bean.agentBean.*;   // OAA Library

public class Frame1 extends Frame {

  Button btnConnect = new Button();   // Connect Button
  AgentBean oaa = new AgentBean();    // OAA bean

  public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try  {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

//Component initialization
  private void jbInit() throws Exception  {
    this.setTitle("Fax Agent");
    this.setLayout(null);
    this.setSize(new Dimension(399, 123));

    // Declaring agent name and capabilities
    oaa.setOaaName("fax");
    oaa.setOaaSolvables("[fax(Destination,Document)]");
    oaa.setOaaHost("trestle");
    oaa.setOaaPort(3344);

    // Setup connection button
    btnConnect.setLabel("Connect");
    btnConnect.setBounds(new Rectangle(0, 20, 399, 40));
    btnConnect.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        oaa.connect();                        // Connect to Facilitator
        oaa.lib.writeBB("noun",     "[fax,fax]"); // Registers vocabulary
        oaa.lib.writeBB("imp_verb", "[fax,fax]"); // Registers vocabulary
      }
    });
    this.add(btnConnect, null);

    // Attache event callback
    oaa.addDoListener(new oaa.agents.bean.agentBean.DoListener() {
      public java.lang.String doEvent(DoEvent e) {
        return oaa_doEvent(e);
      }
    });

  }

//Overriden so we can exit on System Close
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }

  // Pretend to send a document to faxNumber
  boolean myFaxAPI(String faxNum, String doc) {
     return true;
  }

  // Defining the capabilities registered with Facilitator
  String oaa_doEvent(DoEvent e) {

    // fax(Person, Document)
    if (e.func.compareTo("fax") == 0) {
       String person = oaa.lib.nthElt(e.args, 1);  // pull out args
       String doc = oaa.lib.nthElt(e.args, 2);

       // see if we can find fax number for person
       String res = oaa.lib.solve("fax_num(" + person + ",N)", "[]");

       // If OK, pull out result and call our low-level fax API
       if (res.compareTo("[]") != 0) {
          String faxNum = oaa.lib.argument(oaa.lib.listToTerms(res), 2);

          if (myFaxAPI(faxNum, doc))
	           return "["+e.func+"("+e.args+")]";   // return success
       }
    }
    return "[]";	// return failure
  }
}


